package com.ktgj.train.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ktgj.common.core.annotation.Excel;
import com.ktgj.common.core.constant.BusinessTypeConstants;
import com.ktgj.common.core.constant.CustomerConstants;
import com.ktgj.common.core.constant.FlightOrderChangeConstants;
import com.ktgj.common.core.constant.FlightOrderConstants;
import com.ktgj.common.core.domain.R;
import com.ktgj.common.core.enums.EmHelper;
import com.ktgj.common.core.enums.EnumHelper;
import com.ktgj.common.core.enums.TrainOrderEnum;
import com.ktgj.common.core.utils.DateCalcUtils;
import com.ktgj.common.core.utils.SnowFlake;
import com.ktgj.common.core.utils.SnowflakeUtils;
import com.ktgj.common.redis.service.RedisService;
import com.ktgj.customer.api.RemoteCustomerService;
import com.ktgj.customer.api.domain.*;
import com.ktgj.pay.api.RemotePayService;
import com.ktgj.pay.api.domain.*;
import com.ktgj.train.common.TrainTickets;
import com.ktgj.train.domain.*;
import com.ktgj.train.domain.InterfaceEntity.*;
import com.ktgj.train.domain.trainlist.TrainList;
import com.ktgj.train.domain.vo.*;

import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;

import com.ktgj.train.domain.vo.TrainOrderItemVo;
import com.ktgj.train.mapper.*;
import com.ktgj.train.service.ITrainOrderAssistService;
import com.ktgj.train.service.ITrainOrderRefundrecordService;
import com.ktgj.train.service.ITrainOrderitemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ktgj.train.service.ITrainOrderService;

import javax.servlet.http.HttpServletRequest;

/**
 * 订单Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-11-29
 */
@Service
public class TrainOrderServiceImpl implements ITrainOrderService
{
    static final Logger logger = LoggerFactory.getLogger(TrainOrderServiceImpl.class);

    @Autowired
    private TrainOrderMapper trainOrderMapper;

    @Autowired
    private TrainTickets trainTickets;

    @Autowired
    private ITrainOrderService trainOrderService;

    @Autowired
    private ITrainOrderitemService trainOrderItemService;

    @Autowired
    private TrainOrderitemMapper trainOrderitemMapper;

    @Autowired
    private TrainOrderPaymentdetailMapper trainOrderPaymentdetailMapper;

    @Autowired
    private RemoteCustomerService remoteCustomerService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private ITrainOrderRefundrecordService trainOrderRefundrecordService;

    @Autowired
    private RemotePayService payService;

    @Autowired
    private TrainOrderOperationMapper trainOrderOperationMapper;

    @Autowired
    private ITrainOrderAssistService trainOrderAssistService;

    @Autowired
    private TrainOrderRefundrecordMapper trainOrderRefundrecordMapper;


    /**
     * 查询订单
     * 
     * @param orderid 订单ID
     * @return 订单
     */
    @Override
    public TrainOrder selectTrainOrderById(Long orderid) {
        return trainOrderMapper.selectTrainOrderById(orderid);
    }

    /**
     * 查询订单列表
     * 
     * @param trainOrder 订单
     * @return 订单
     */
    @Override
    public List<TrainOrder> selectTrainOrderList(TrainOrder trainOrder) {
        return trainOrderMapper.selectTrainOrderList(trainOrder);
    }

    /**
     * 新增订单
     * 
     * @param trainOrder 订单
     * @return 结果
     */
    @Override
    public int insertTrainOrder(TrainOrder trainOrder) {
        return trainOrderMapper.insertTrainOrder(trainOrder);
    }

    /**
     * 修改订单
     * 
     * @param trainOrder 订单
     * @return 结果
     */
    @Override
    public int updateTrainOrder(TrainOrder trainOrder) {
        return trainOrderMapper.updateTrainOrder(trainOrder);
    }

    @Override
    public int updateByTrainOrder(TrainOrderVo trainOrderVo) {
        return trainOrderMapper.updateByTrainOrder(trainOrderVo);
    }

    /**
     * 批量删除订单
     * 
     * @param orderids 需要删除的订单ID
     * @return 结果
     */
    @Override
    public int deleteTrainOrderByIds(Long[] orderids) {
        return trainOrderMapper.deleteTrainOrderByIds(orderids);
    }

    /**
     * 删除订单信息
     * 
     * @param orderid 订单ID
     * @return 结果
     */
    @Override
    public int deleteTrainOrderById(Long orderid) {
        return trainOrderMapper.deleteTrainOrderById(orderid);
    }

    //填写订单
    @Override
    public TrainFillOrder fillOrder(String token, QueryTrainSeatRequest request) {
        TrainFillOrder trainFillOrder = new TrainFillOrder();
        try {
            TrainList trainList = trainTickets.queryTrainSeat(request);
            trainFillOrder.setTrainList(trainList);
            R<Customer> customer = remoteCustomerService.getLoginCustomerByToken(token);
            SeatPrice price = new SeatPrice();
            price.fromStationName = request.fromStationName;
            price.toStationName = request.toStationName;
            price.train_code = request.train_code;
            price.train_date = request.train_date;
            price.seat = request.seat;
            BigDecimal seatPrice = trainTickets.seatPrice(price);
            trainFillOrder.setSMSnotification(customer.getData().getContractPhoneOne());
            R<Long> depb = remoteCustomerService.queyUserDepositBusinessByToken(token);
            if (depb.getCode() == 200) {
                Long depositBusiness = depb.getData();
                trainFillOrder.setDepositBusiness(depositBusiness);
            }

            R<Long> integralVoR = remoteCustomerService.queyUserCreditsNumByToken(token);
            if (integralVoR.getCode() == 200) {
                Long points = integralVoR.getData();
                trainFillOrder.setPoints(points);
            }

            R<CouponDto> couponDtoR = remoteCustomerService.queyUserCouponByToken(token, seatPrice);
            if (couponDtoR.getCode() == 200) {
                CouponDto data = couponDtoR.getData();
                trainFillOrder.setCoupon(data);
            }


        } catch (Exception e) {
            e.getMessage();
        }
        return trainFillOrder;
    }

    //生成订单
    @Override
    public Order createOrder(String token, GenerateOrder request) throws Exception {
        Order order = new Order();
        TrOrderSubmissionResponse response = new TrOrderSubmissionResponse();
        TrainOrder trainOrder = new TrainOrder();
        TrainOrderitem trainOrderitem = new TrainOrderitem();
        R<Customer> customer;
        if (request.customerId != null && request.customerId != 0){
            customer = remoteCustomerService.getCustomerId(request.customerId);
        }
        else {
            customer = remoteCustomerService.getLoginCustomerByToken(token);
        }
        if (customer.getData() == null){
            throw new Exception("登录已过期");
        }
        SnowFlake snowFlake = new SnowFlake(3, 3);
        Long orderNo = snowFlake.nextId();
        Long orderId = snowFlake.nextId();
        String orderType = "购买火车票";
        String orderSourceDesc = request.checi + request.from_station_name + request.to_station_name;

        SimpleDateFormat dateFormat = new SimpleDateFormat("HHmmssSSS");
        String reqtime = dateFormat.format(new Date());
        //需要生成几位
        int n = 5;
        //最终生成的字符串
        String reqstr = "";
        for (int i = 0; i < n; i++) {
            reqstr = reqstr + (char) (Math.random() * 26 + 'a');
        }

        SeatPrice seatPrice = new SeatPrice();
        seatPrice.train_date = request.train_date;
        seatPrice.fromStationName = request.from_station_name;
        seatPrice.toStationName = request.to_station_name;
        seatPrice.train_code = request.checi;
        seatPrice.seat = request.zwcode;

        //票价
        BigDecimal bigDecimal = trainTickets.seatPrice(seatPrice);
        //总价
        BigDecimal multiply = bigDecimal.multiply(new BigDecimal(request.passengerLists.size()));

        //优惠金额
        BigDecimal countPrice = null;
        if (request.couponId != null && request.couponId != 0) {
            trainOrder.setCouponId(request.couponId);

            R<CouponDto> couponDtoR;
            if (token != null && !token.equals("")){
                couponDtoR = remoteCustomerService.queyUserCouponByToken(token, bigDecimal);
            }
            else {
                couponDtoR = remoteCustomerService.queyUserCouponById(request.customerId, bigDecimal);
            }

            if (couponDtoR.getCode() != 500){
                if (couponDtoR.getData().getCouponType().equals(CustomerConstants.CouponTypeFullMinus.getValue()) || couponDtoR.getData().getCouponType().equals(CustomerConstants.CouponTypeCashCoupon.getValue())) {
                    countPrice = new BigDecimal(couponDtoR.getData().getCouponPrice());
                } else {
                    Long price = couponDtoR.getData().getCouponDiscount();
                    Long divide = price / 100;
                    countPrice = multiply.multiply(new BigDecimal(divide));
                }
            }
            trainOrder.setCouponAmount(countPrice);
        }
        CustomerIdVoApi customerIdVoApi = new CustomerIdVoApi();
        customerIdVoApi.setCustomerId(customer.getData().getCustomerId());
//        CustomerIdVoApi customerIdApi = remoteCustomerService.customerIdApi(customerIdVoApi);
        //辅营产品
        List<BigDecimal> additionalList = new ArrayList<>();
        if (request.products != null && request.products.size() > 0) {
            for (AuxiliaryProducts products : request.products) {
                R<AssistProductApi> productApiR = remoteCustomerService.queryAssistProduct(products.getProductId());
                BigDecimal insuranceamount = productApiR.getData().getSalePrice();
                additionalList.add(insuranceamount);
//                if (customerIdApi != null) {
//                    BigDecimal insuranceamount = productApiR.getData().getSalePrice();
//                    additionalList.add(insuranceamount);
//                    if (customerIdApi.getLevel().equals("1")) {
//                        BigDecimal insuranceamount = productApiR.getData().getSalePrice();
//                        additionalList.add(insuranceamount);
//                    } else {
//                        BigDecimal insuranceamount = productApiR.getData().getMemberPrice();
//                        additionalList.add(insuranceamount);
//                    }
//                }
            }
        }
        //金币
        BigDecimal depositSkipPwdAmount = new BigDecimal(0);
        R<Long> longR;
        if (token != null && !token.equals("")){
            longR = remoteCustomerService.queyUserDepositBusinessByToken(token);
        }
        else {
            longR = remoteCustomerService.selectAvailableGoldByCustomerId(request.customerId);
        }
        if (longR.getData() != null) {
            depositSkipPwdAmount = new BigDecimal(longR.getData());
            if (request.useDeposit) {
                trainOrder.setDepositAmount(depositSkipPwdAmount);
            }
        }

        //积分
        BigDecimal points;
        R<Long> pntValueR;
        if (token != null && !token.equals("")){
            pntValueR = remoteCustomerService.queyUserCreditsNumByToken(token);
        }
        else {
            pntValueR = remoteCustomerService.queyUserCreditsNumByCustomerId(request.customerId);
        }

        Long pntValue = pntValueR.getData();
        if (pntValue != null) {
            points = new BigDecimal(pntValue);
            if (request.usePoint) {
                trainOrder.setPoints(points);
            }
        }

        //服务费
        BigDecimal serviceCharge = new BigDecimal(5);
        trainOrder.setServiceCharge(serviceCharge);

        CalculationVOApi calculationVOApi = new CalculationVOApi();
        if (request.type != null && request.type.equals("Crm")){
            List<BigDecimal> unitPriceList = new ArrayList<>();
            unitPriceList.add(bigDecimal);
            unitPriceList.add(serviceCharge);
            calculationVOApi.setPrices(unitPriceList);//商品单价集合
            calculationVOApi.setAmount(request.passengerLists.size());//商品数量
            calculationVOApi.setAdditionalPrices(additionalList);//附加商品单价集合
            calculationVOApi.setAdditionalAmount(1);//附加商品数量
            calculationVOApi.setCouponId(0l);//优惠卷id
            calculationVOApi.setDepositAmount(new BigDecimal(0));//用户拥有的金币数量
            calculationVOApi.setUseDeposit(false);//是否使用金币
            calculationVOApi.setPointAmount(0);//用户拥有的积分数量
            calculationVOApi.setUsePoint(false);//是否使用积分
        }
        else {
            List<BigDecimal> unitPriceList = new ArrayList<>();
            unitPriceList.add(bigDecimal);
            unitPriceList.add(serviceCharge);
            calculationVOApi.setPrices(unitPriceList);//商品单价集合
            calculationVOApi.setAmount(request.passengerLists.size());//商品数量
            calculationVOApi.setAdditionalPrices(additionalList);//附加商品单价集合
            calculationVOApi.setAdditionalAmount(1);//附加商品数量
            calculationVOApi.setCouponId(request.couponId);//优惠卷id
            calculationVOApi.setDepositAmount(depositSkipPwdAmount);//用户拥有的金币数量
            calculationVOApi.setUseDeposit(request.useDeposit);//是否使用金币
            if (pntValue != null) {
                calculationVOApi.setPointAmount(Integer.parseInt(pntValue.toString()));//用户拥有的积分数量
            } else {
                calculationVOApi.setPointAmount(0);
            }
            calculationVOApi.setUsePoint(request.usePoint);//是否使用积分
        }

        CalculationDTO calculationDTO = remoteCustomerService.calculationRemotely(calculationVOApi);
        BigDecimal couponAmount = calculationDTO.getPrice();

        BigDecimal payamount = new BigDecimal(request.payamount.toString());
        if (couponAmount.compareTo(payamount) != 0){
            throw new Exception("支付价格出现变动");
        }

        //生成订单
        trainOrder.setOrderid(orderId); //订单id
        trainOrder.setJsjid(customer.getData().getCustomerId()); //会员编号
        trainOrder.setTraveldate(request.train_date); //乘车日期
        trainOrder.setArrivalstationname(request.to_station_name); //到达车站
        trainOrder.setDeparturestationcode(request.fromCode);
        trainOrder.setArrivalstationcode(request.toCode);
        trainOrder.setDeparturetime(request.start_time); //出发时间
        trainOrder.setChooesseats(request.choose_seats); //座位号  选座STR（比如：1A1D2B2C2F，就是选5个坐席），选座个数要与乘客数量应该一致
        trainOrder.setDeparturestationname(request.from_station_name); //出发车站
        trainOrder.setTrainnumber(request.checi); //车次号
        trainOrder.setArrivaltime(request.arrive_time); //到达时间
        trainOrder.setIsacceptstanding(request.is_accept_standing); //是否要无座票
        trainOrder.setOrdernumber(String.valueOf(orderNo)); //订单编号
        trainOrder.setSmsnotify(0); //预订车票完成并付款成功是否短信通知用户
        trainOrder.setIspending(0L); //0表示正常 1表示异常
        trainOrder.setTicketprice(bigDecimal); //票单价
        trainOrder.setLinkname(customer.getData().getCustomerName()); //联系人名
        trainOrder.setLinkphone(customer.getData().getContractPhoneOne()); //联系人手机
        trainOrder.setSeattype(request.zwcode); //0、无座 1、硬座 2、软座 3、硬卧 4、软卧 5、包厢硬卧 6、高级软卧 7、一等软座 8、二等软座 9、商务座 A、高级动卧 E、特等软座 F、动卧 H、一人软包 I、一等卧 J、二等卧 M、一等座 O、二等座 P、特等座 Q、多功能座
        int size = request.passengerLists.size();
        trainOrder.setSumamount(bigDecimal.multiply(BigDecimal.valueOf(size))); //总价
        trainOrder.setPayamount(new BigDecimal(0.1)); //TODO 测试暂时写死0.1
        trainOrder.setPaymentorderstatus(TrainOrderEnum.unpaid.getValue()); //"支付状态:未支付 = 1, 支付中 = 2,  预授权成功 = 3,  预授权消费完成 = 4, 预授权失败 = 5,  预授权撤销 = 6, 退款中 = 7, 退款完成 = 8, 退款失败 = 9
        trainOrder.setCreateTime(new Date()); //创建时间
        trainOrder.setUpdateTime(new Date()); //更新时间
        trainOrder.setOpemployeeid(1L); //操作人
        trainOrder.setStatus(TrainOrderEnum.unpaid.getValue()); //Order订单状态: 未支付 = 10, 支付中 = 20, 支付成功 = 30, 出票成功 = 40, 出票失败 = 50, 取消订单 = 60
        trainOrder.setRequestpayoutstatus(0); //请款状态
        trainOrder.setIsgiveinsurance(0); //是否赠送保险
        trainOrder.setLinkphone(request.SMSnotification); //联系人手机
        trainOrder.setAddday(request.addDay);
        request.orderid = "jsj" + reqtime;
        trainOrder.setMerchantOrderId(request.orderid); //商户订单号
        request.reqtoken = reqstr + reqtime;
        trainOrder.setReqtoken(request.reqtoken); //请求特征值
        if (token != null) {
            trainOrder.setSourceappid("App");
        } else {
            trainOrder.setSourceappid("Crm");
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date start_time = format.parse(request.train_date + " " + request.start_time);
        Date arrive_time;
        if (request.addDay == 0) {
            arrive_time = format.parse(request.train_date + " " + request.arrive_time);
        } else {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = simpleDateFormat.parse(request.train_date);
            Date add = DateCalcUtils.addDay(date, new Long(request.addDay).intValue());
            String formats = simpleDateFormat.format(add);
            arrive_time = format.parse(formats + " " + request.arrive_time);
        }
        long diff = arrive_time.getTime() - start_time.getTime();
        long diffMinutes = diff / (60 * 1000) % 60;
        long diffHours = diff / (60 * 60 * 1000) % 24;
        long diffDays = diff / (24 * 60 * 60 * 1000);
        StringBuffer stringBuffer = new StringBuffer();
        if (diffDays > 0) {
            diffHours = diffDays * 24 + diffHours;
            stringBuffer.append(diffHours + "时");
            stringBuffer.append(diffMinutes + "分");
            trainOrder.setRunTime(stringBuffer.toString());
        } else {
            stringBuffer.append(diffHours + "时");
            stringBuffer.append(diffMinutes + "分");
            trainOrder.setRunTime(stringBuffer.toString());
        }

        for (PassengerList passengerList : request.passengerLists) {
            List<CommonPassengerApi> commonPassengerApis = remoteCustomerService.queryPassengerByCustomerId(customer.getData().getCustomerId(), Long.valueOf(passengerList.commonTrvelersId), passengerList.certificateType);
            for (CommonPassengerApi commonPassengerApi : commonPassengerApis) {
                Passengers passenger = new Passengers();
                SnowflakeUtils snowflakeUtils = new SnowflakeUtils();
                passenger.passengersename = commonPassengerApi.getChineseName();
                passenger.passportseno = commonPassengerApi.getCertificateNumber();
                if (commonPassengerApi.getCertificateType().equals("ID_CARD")) {
                    passenger.passporttypeseid = "1";
                } else if (commonPassengerApi.getCertificateType().equals("RPFHKMATR")) {
                    passenger.passporttypeseid = "2";
                } else if (commonPassengerApi.getCertificateType().equals("MTPFHKAMR")) {
                    passenger.passporttypeseid = "C";
                } else if (commonPassengerApi.getCertificateType().equals("MTPFTR")) {
                    passenger.passporttypeseid = "G";
                } else if (commonPassengerApi.getCertificateType().equals("PASSPORT")) {
                    passenger.passporttypeseid = "B";
                } else if (commonPassengerApi.getCertificateType().equals("PRICFF")) {
                    passenger.passporttypeseid = "H";
                }
                passenger.passporttypeseidname = commonPassengerApi.getCertificateName();
                passenger.passengerid = String.valueOf(System.currentTimeMillis());
                passenger.zwcode = request.zwcode;
                if (request.zwcode.equals("9")) {
                    passenger.zwname = "商务座";
                } else if (request.zwcode.equals("P")) {
                    passenger.zwname = "特等座";
                } else if (request.zwcode.equals("M")) {
                    passenger.zwname = "一等座";
                } else if (request.zwcode.equals("O")) {
                    passenger.zwname = "二等座";
                } else if (request.zwcode.equals("6")) {
                    passenger.zwname = "高级软卧";
                } else if (request.zwcode.equals("F")) {
                    passenger.zwname = "动卧";
                } else if (request.zwcode.equals("4")) {
                    passenger.zwname = "软卧";
                } else if (request.zwcode.equals("3")) {
                    passenger.zwname = "硬卧";
                } else if (request.zwcode.equals("2")) {
                    passenger.zwname = "软座";
                } else if (request.zwcode.equals("E")) {
                    passenger.zwname = "特等软座";
                } else if (request.zwcode.equals("1")) {
                    passenger.zwname = "硬座";
                } else if (request.zwcode.equals("I")) {
                    passenger.zwname = "一等卧";
                } else if (request.zwcode.equals("J")) {
                    passenger.zwname = "二等卧";
                } else if (request.zwcode.equals("A")) {
                    passenger.zwname = "高级动卧";
                } else if (request.zwcode.equals("5")) {
                    passenger.zwname = "包厢硬卧";
                } else if (request.zwcode.equals("H")) {
                    passenger.zwname = "一人软包";
                } else if (request.zwcode.equals("7")) {
                    passenger.zwname = "一等软座";
                } else if (request.zwcode.equals("8")) {
                    passenger.zwname = "二等软座";
                } else if (request.zwcode.equals("0")) {
                    passenger.zwname = "无座";
                } else if (request.zwcode.equals("Q")) {
                    passenger.zwname = "多功能座";
                }
                passenger.price = bigDecimal.doubleValue();
                String piaotype = "";
                if (commonPassengerApi.getTicketType().equals("aldult")) {
                    piaotype = passenger.piaotype = "1";
                }
                if (commonPassengerApi.getTicketType().equals("child")) {
                    piaotype = passenger.piaotype = "2";
                }
                passenger.cxin = "";
                passenger.phoneNum = request.SMSnotification;
                request.passengers.add(passenger);
                //生成子订单
                trainOrderitem.setOrderitemid(snowflakeUtils.nextId()); //主键编号
                trainOrderitem.setOrderid(orderId); //关联主表编号
                trainOrderitem.setOrderitemnumber(String.valueOf(System.currentTimeMillis())); //子订单号
                trainOrderitem.setStatus(TrainOrderEnum.unpaid.getValue());
                trainOrderitem.setSeattype(request.zwcode);

                trainOrderitem.setOpemployeeid(1L);
                trainOrderitem.setCreateTime(new Date());
                trainOrderitem.setUpdateTime(new Date());
                trainOrderitem.setTickettype(Long.valueOf(piaotype));
                trainOrderitem.setGuestname(commonPassengerApi.getChineseName());
                trainOrderitem.setIdnumber(commonPassengerApi.getCertificateNumber());
                trainOrderitem.setIdtype(commonPassengerApi.getCertificateType());
                trainOrderitemMapper.insertTrainOrderitem(trainOrderitem);
                if (request.products != null && request.products.size() > 0) {
                    request.products.forEach(item -> {
                        if (commonPassengerApi.getCertificateNumber().equals(item.getIdNo())) {
                            R<AssistProductApi> assistProductApiR = remoteCustomerService.queryAssistProduct(item.getProductId());
                            AssistProductApi productApi = assistProductApiR.getData();
                            if (assistProductApiR.getCode() == 200 && productApi != null) {
                                TrainOrderAssist orderAssist = new TrainOrderAssist();
                                orderAssist.setName(productApi.getName());
                                orderAssist.setPrice(productApi.getSalePrice());
//                                if (customerIdApi.getLevel().equals("1")) {
//                                    orderAssist.setPrice(productApi.getSalePrice());
//                                } else {
//                                    orderAssist.setPrice(productApi.getMemberPrice());
//                                }
                                orderAssist.setAssistProductId(item.getProductId());
                                orderAssist.setOrderItemID(trainOrderitem.getOrderitemid());
                                if (productApi.getProductTypeid() != null && productApi.getProductTypeid() != 0) {
                                    orderAssist.setInsType(productApi.getProductType());
                                }
                                orderAssist.setStatus("wait");
                                trainOrderAssistService.insertTrainOrderAssist(orderAssist);
                            }
                        }
                    });
                }
            }
        }
        if ((pntValue != null && pntValue.longValue() > 0L) || request.couponId != null || (longR.getData() != null && longR.getData().longValue() > 0L)) {
            BigDecimal decimal = new BigDecimal(0);
            if (longR.getData() != null){
                decimal = new BigDecimal(longR.getData());
            }
            remoteCustomerService.spend(customer.getData().getCustomerId(), pntValue, orderType, trainOrder.getOrderid(), orderSourceDesc, request.couponId, decimal, 1L);
        }
        redisService.setCacheObject("train" + customer.getData().getCustomerId() + "o" + trainOrder.getOrdernumber(), JSON.toJSON(trainOrder), 60 * 10L, TimeUnit.SECONDS);
        try {
            R<CustomeraccountApi> customerAccount = remoteCustomerService.queryAccountIdAndAccountPassword(customer.getData().getCustomerId(), CustomerConstants.trianAccount.getValue());
            if (customerAccount.getData().getAccountId() != null && customerAccount.getData().getAccountPassword() != null) {
                String trainAccount = customerAccount.getData().getAccountId();
                String trainPassword = customerAccount.getData().getAccountPassword();
                request.LoginUserName = trainAccount;
                request.LoginUserPassword = trainPassword;
                response = trainTickets.orderSubmissions(request);
            }
        } catch (Exception e) {
            response.msg = e.getMessage() + e.getStackTrace();
        }
        trainOrder.setOrderpartnernumber(response.orderid);
        trainOrder.setOrdersuccess("false");
        trainOrder.setMsg("占座中");
        int insertTrainOrder = trainOrderMapper.insertTrainOrder(trainOrder);
        if (insertTrainOrder > 0) {
            TrainOrderOperation orderOperation = new TrainOrderOperation();
            orderOperation.setOperationname("创建订单成功");
            orderOperation.setOrderid(orderId);
            orderOperation.setOpemployeeid(1L);
            if (request.customerId != null && request.customerId != 0)
                orderOperation.setOpemployeename("系统服务");
            else
                orderOperation.setOpemployeename("会员");
            orderOperation.setCreateTime(new Date());
            trainOrderOperationMapper.insertTrainOrderOperation(orderOperation);
        }

        if (response.success.equals("true")) {
            /*String str = "";
            while (str.equals("")) {
                Thread.sleep(1000);
                if (redisService.getCacheObject(request.reqtoken) != null) {
                    str = redisService.getCacheObject(request.reqtoken).toString();
                    redisService.deleteObject(request.reqtoken);
                }
            }*/
            if (customer.getData().getCustomerId()!=null && customer.getData().getCustomerId()!=0l) {
                //会员消息
                Map<String, String> messageMap = new HashMap<>();
                String customerName = customer.getData().getCustomerName();
                String star = "乘客" + customerName + "你好," + "你订购的"+request.checi+"列车"+"cong" +request.from_station_name + "到" + request.to_station_name + "的火车票" + "出发时间为：" +request.train_date+" "+request.start_time + "请在规定时间内支付，以免影响您的行程";
                messageMap.put("messageContent", star);
                //订单类型
                messageMap.put("businessType", BusinessTypeConstants.train.getValue());
                messageMap.put("customerId",customer.getData().getCustomerId().toString());
                messageMap.put("businessOrderId",trainOrder.getOrdernumber());
                remoteCustomerService.addCustomerMessage(messageMap);
                /*if (remoteCustomerService.addCustomerMessage(map1)>0)
                {
                    logger.info("添加会员消息成功！");
                }else
                {
                    logger.info("添加会员消息失败！");
                }*/
            }
            order.setOrderNumber(trainOrder.getOrdernumber());
            order.setMsg(response.msg);
            order.setSuccess(response.success);
            order.setRequest(request);

            TrainOrderOperation orderOperation = new TrainOrderOperation();
            orderOperation.setOperationname("车票预定");
            orderOperation.setOrderid(orderId);
            orderOperation.setOpemployeeid(1L);
            if (request.customerId != null && request.customerId != 0)
                orderOperation.setOpemployeename("系统服务");
            else
                orderOperation.setOpemployeename("会员");
            orderOperation.setCreateTime(new Date());
            trainOrderOperationMapper.insertTrainOrderOperation(orderOperation);
        } else {
            order.setOrderNumber(trainOrder.getOrdernumber());
            order.setMsg(response.msg);
            order.setSuccess(response.success);
            order.setRequest(request);
        }
        return order;
    }

    @Override
    public TrainOrderVo queryOrderDetail(String orderNumber) {
        BigDecimal ticketPrice = new BigDecimal(0);
        TrainOrderVo trainOrderVo = trainOrderMapper.queryOrderDetail(orderNumber);
        Integer orderItemCount = trainOrderMapper.queryCountOrderItem(orderNumber);
        BigDecimal orderCount = new BigDecimal(orderItemCount);
        for (TrainOrderItemVo trainOrderItemVo : trainOrderVo.getTrainOrderItemVoList()) {
            ticketPrice = trainOrderItemVo.getTicketPrice();
        }
        trainOrderVo.setSumAmount(ticketPrice.multiply(orderCount));
        trainOrderVo.setPayAmount(trainOrderVo.getSumAmount());
        return trainOrderVo;
    }

    //取消订单
    @Override
    public TrainStayOutTicket cancelOrder(String token, TrCancellationOrderRequest request) {
        TrainStayOutTicket ticket = new TrainStayOutTicket();
        TrCancellationOrderResponse response = new TrCancellationOrderResponse();
        try {
            TrainOrder trainorder = null;
            Long customerId = null;
            if (token != null){
                R<Customer> customer = remoteCustomerService.getLoginCustomerByToken(token);
                customerId = customer.getData().getCustomerId();
                trainorder = trainOrderMapper.queryTrainOrder(customerId, request.orderNumber);
            }
            else {
                customerId = request.customerId;
                trainorder = trainOrderMapper.queryTrainOrder(customerId, request.orderNumber);
            }
            request.transactionid = trainorder.getOrderpartnernumber();
            request.orderid = trainorder.getMerchantOrderId();
            response = trainTickets.cancellationOrder(request);
            TrainOrderVo trainOrderVo = queryOrderDetail(request.orderNumber);
            if (response.success.equals("true")) {
                trainOrderVo.setStatus(TrainOrderEnum.cancelOrder.getValue());
                TrainOrderitem orderitem = new TrainOrderitem();
                orderitem.setOrderid(trainOrderVo.getOrderId());
                orderitem.setStatus(TrainOrderEnum.cancelOrder.getValue());
                trainOrderItemService.updateByOrderId(orderitem);
                trainOrderService.updateByTrainOrder(trainOrderVo);
                TrainOrder order = trainOrderMapper.queryTrainOrder(customerId, request.orderNumber);
                ticket.setOrderNumber(request.orderNumber);
                ticket = queryOrder(ticket, order);

                TrainOrderOperation orderOperation = new TrainOrderOperation();
                orderOperation.setOperationname("取消订单");
                orderOperation.setOrderid(trainorder.getOrderid());
                orderOperation.setOpemployeeid(1L);
                if (request.customerId != null && request.customerId != 0)
                    orderOperation.setOpemployeename("系统服务");
                else
                    orderOperation.setOpemployeename("会员");
                orderOperation.setCreateTime(new Date());
                trainOrderOperationMapper.insertTrainOrderOperation(orderOperation);
            }
        } catch (Exception e) {
            response.msg = e.getMessage();
        }
        return ticket;
    }

    /**
     * 火车票（退票）
     * */
    @Override
    public OrderDetailsVo refundApplication(Long orderid) {
        TrainOrder trainOrder = trainOrderMapper.selectTrainOrderByOrderID(orderid);
        List<TrainOrderitem> trainOrderitemList = trainOrderitemMapper.selectTrainOrderitemByOrderId(orderid);
        TrainOrderPaymentdetail trainOrderPaymentdetail = trainOrderPaymentdetailMapper.selectTrainOrderPaymentdetailByOrderId(orderid);
        TrOutTicketRequest request = new TrOutTicketRequest();
        request.transactionid = trainOrder.getOrdernumber();//订单号
        request.orderid = "123456";//商户订单号
        TrOutTicketResponse trOutTicketResponse = trainTickets.outTicket(request);
        OrderDetailsVo orderDetailsVo = new OrderDetailsVo();
        List<OrderitemVo> orderitemVoList = new CopyOnWriteArrayList<>();
        //orderDetailsVo.setStatus(status(trainOrder.getStatus()));//订单状态
        orderDetailsVo.setOrdernumber(trainOrder.getOrdernumber());//订单编号
        orderDetailsVo.setTicketNumber(trOutTicketResponse.ordernumber);//取票号
        orderDetailsVo.setFare("￥1678x1");//车费 todo 李博洋
        orderDetailsVo.setTicketGrabbingFee("￥20x1");//抢票费 todo 李博洋
        orderDetailsVo.setTrainAccidentInsurance("￥20x1");//火车意外险 todo 李博洋
        orderDetailsVo.setTrainnumber(trainOrder.getTrainnumber());//车次号
        orderDetailsVo.setDeparturestationname(trainOrder.getDeparturestationname());//出发车站
        orderDetailsVo.setArrivalstationname(trainOrder.getArrivalstationname());//到达车站
        orderDetailsVo.setDeparturetime(trainOrder.getDeparturetime().substring(6, 11));//出发时间
        orderDetailsVo.setArrivaltime(trainOrder.getArrivaltime().substring(6, 11));//到达时间
        orderDetailsVo.setDepartureDate(trainOrder.getDeparturetime().substring(0, 5));//出发日期
        orderDetailsVo.setArrivalDate(trainOrder.getArrivaltime().substring(0, 5));//到达日期
        orderDetailsVo.setSumamount("￥"+trainOrder.getSumamount().toString().substring(0, trainOrder.getSumamount().toString().indexOf(".")));//总价
        orderDetailsVo.setPayamount("￥"+trainOrder.getPayamount().toString().substring(0, trainOrder.getPayamount().toString().indexOf(".")));//支付价
        orderDetailsVo.setDepositSkipPwdAmount("￥"+trainOrderPaymentdetail.getSetasideamount().toString().substring(0, trainOrderPaymentdetail.getSetasideamount().toString().indexOf(".")));//预留款

        for (TrainOrderitem trainOrderitem : trainOrderitemList) {
            OrderitemVo orderitemVo = new OrderitemVo();
            orderitemVo.setGuestname(trainOrderitem.getGuestname());//乘客姓名
            orderitemVo.setIdnumber(trainOrderitem.getIdnumber());//身份证号
            orderitemVo.setSeatno(trainOrderitem.getTrainbox()+"车厢"+trainOrderitem.getSeatno()+"号");//座位号
            orderitemVo.setTickettype(trainOrderitem.getTickettype());//车票类型 0成人票 1儿童票
            orderitemVo.setSeattype(trainOrderitem.getSeattype());//坐席类型
            orderitemVo.setPayamount("￥"+trainOrderitem.getPayamount());//支付单票的金额，出票成功后回填
            orderitemVo.setStatus(status(trainOrderitem.getStatus()));//状态
            orderitemVoList.add(orderitemVo);
        }

        orderDetailsVo.setTrainOrderitemVoList(orderitemVoList);
        return orderDetailsVo;
    }

    //订单详情
    @Override
    public TrainStayOutTicket queryTrainOrder(String token, String orderNumber, Long customerId) {
        TrainStayOutTicket ticket = new TrainStayOutTicket();
        try {
            if (token != null && customerId == 0) {
                R<Customer> customer = remoteCustomerService.getLoginCustomerByToken(token);
                TrainOrder order = trainOrderMapper.queryTrainOrder(customer.getData().getCustomerId(), orderNumber);
                ticket.setOrderNumber(orderNumber);
                ticket = queryOrder(ticket, order);
            } else {
                TrainOrder order = trainOrderMapper.queryTrainOrder(customerId, orderNumber);
                ticket.setOrderNumber(orderNumber);
                ticket = queryOrder(ticket, order);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        Map<String, Object> map = new HashMap<>();
        map.put("id", customerId);
        BigDecimal bigDecimal = remoteCustomerService.dominateGold(map);
        ticket.setDepositAmount(bigDecimal);
        return ticket;
    }

    //退票申请
    @Override
    public RetreatTicket retreat(String token, Long customerId, String orderNumber) {
        RetreatTicket ticket = new RetreatTicket();
        TrainOrder order = null;
        if (token != null) {
            R<Customer> customer = remoteCustomerService.getLoginCustomerByToken(token);
            order = trainOrderMapper.queryTrainOrder(customer.getData().getCustomerId(), orderNumber);
        } else {
            order = trainOrderMapper.queryTrainOrder(customerId, orderNumber);
        }
        ticket.setTrainNumber(order.getTrainnumber());
        ticket.setDepartureStationName(order.getDeparturestationname());
        ticket.setArrivalStationName(order.getArrivalstationname());
        ticket.setTicketPrice(order.getTicketprice());
        for (TrainOrderitem trainOrderitem : order.getTrainOrderitemList()) {
            GuestInformation information = new GuestInformation();
            information.setOrderItemID(String.valueOf(trainOrderitem.getOrderitemid()));
            information.setGuestName(trainOrderitem.getGuestname());
            information.setiDNumber(trainOrderitem.getIdnumber());
            information.setTicketType(trainOrderitem.getTickettype());
            information.setSeatType(trainOrderitem.getSeattype());
            information.setTicketNumber(trainOrderitem.getTicketnumber());
            information.setTrainBox(trainOrderitem.getTrainbox());
            information.setSeatNo(trainOrderitem.getSeatno());
            information.setStatus(trainOrderitem.getStatus());
            ticket.getGuestInformations().add(information);
        }
        return ticket;
    }

    //请求退票
    @Override
    public TrRetreatTicketResponse retreatTicket(String token, TrRetreatTicketRequest request) {
        TrainOrder order = null;
        if (token != null) {
            R<Customer> customer = remoteCustomerService.getLoginCustomerByToken(token);
            order = trainOrderMapper.queryTrainOrder(customer.getData().getCustomerId(), request.orderNumber);
        } else {
            order = trainOrderMapper.queryTrainOrder(request.customerId, request.orderNumber);
        }
        request.orderid = order.getMerchantOrderId();
        request.ordernumber = order.getOrder12306number();
        request.reqtoken = order.getReqtoken();
        request.transactionid = order.getOrderpartnernumber();
        SnowFlake snowFlake = new SnowFlake(2, 2);
        for (Long itemId : request.orderItemID) {
            TrainOrderitem orderitem = trainOrderItemService.selectTrainOrderitemById(itemId);
            Tickets ticket = new Tickets();
            ticket.passengername = orderitem.getGuestname();
            ticket.passportseno = orderitem.getIdnumber();
            ticket.passporttypeseid = orderitem.getIdtype();
            ticket.ticket_no = orderitem.getTicketnumber();
            request.tickets.add(ticket);

            TrainOrderRefundrecord refundrecord = new TrainOrderRefundrecord();
            refundrecord.setRecordid(snowFlake.nextId()); //主键编号
            refundrecord.setOrderid(order.getOrderid()); //主订单编号
            refundrecord.setOrderitemid(orderitem.getOrderitemid()); //子订单编号
            refundrecord.setName(orderitem.getGuestname()); //乘客姓名
            refundrecord.setStatus(TrainOrderEnum.processing.getValue());
            refundrecord.setOpemployeeid(1L);
            refundrecord.setCreateTime(new Date());
            refundrecord.setChangeType(FlightOrderChangeConstants.refund.getValue());
            trainOrderRefundrecordService.insertTrainOrderRefundrecord(refundrecord);

        }
        TrRetreatTicketResponse response = trainTickets.retreatTicket(request);
        if (response.success) {
            order.setStatus(TrainOrderEnum.processing.getValue());
            trainOrderMapper.updateTrainOrder(order);

            FinanceOrderRefundment refundment = new FinanceOrderRefundment();
            refundment.setOrderTypeId(Long.valueOf(com.ktgj.common.core.constant.FinanceOrderRefundment.train.getValue()));
            refundment.setCustomerId(order.getJsjid());
            refundment.setRefundmentType(Long.valueOf(com.ktgj.common.core.constant.FinanceOrderRefundment.originalRoad.getValue()));
            refundment.setRefundmentAmount(order.getPayamount()); //TODO 测试，手续费暂为0，后期完善
            refundment.setStatus(com.ktgj.common.core.constant.FinanceOrderRefundment.initial.toString());
            refundment.setOrderId(String.valueOf(order.getOrderid()));
            refundment.setApplyTime(new Date());
            if (order.getPayType().equals(BusinessTypeConstants.BankCredit.getValue())) {
                refundment.setPaymentTypeId("2");
            } else if (order.getPayType().equals(BusinessTypeConstants.BankDebit.getValue())) {
                refundment.setPaymentTypeId("1");
            }
            refundment.setSerialnumber(order.getBillNo());
            remoteCustomerService.add(refundment);

            TrainOrderOperation orderOperation = new TrainOrderOperation();
            orderOperation.setOperationname("申请退票");
            orderOperation.setOrderid(order.getOrderid());
            orderOperation.setOpemployeeid(1L);
            if (request.customerId != null && request.customerId != 0)
                orderOperation.setOpemployeename("系统服务");
            else
                orderOperation.setOpemployeename("会员");
            orderOperation.setCreateTime(new Date());
            trainOrderOperationMapper.insertTrainOrderOperation(orderOperation);
        }
        return response;
    }

    //保存占座回调
    @Override
    public int updateByCallback(TrainOrder trainOrder) {
        return trainOrderMapper.updateByCallback(trainOrder);
    }

    @Override
    public Long selectOrderId(String orderPartnerNumber) {
        return trainOrderMapper.selectOrderId(orderPartnerNumber);
    }

    //收银台
    @Override
    public Cashier queryByPayOrder(String token, String orderNumber, String businessType) {
        Cashier cashier = new Cashier();
        R<Customer> customer = remoteCustomerService.getLoginCustomerByToken(token);
        Long customerId = customer.getData().getCustomerId();
        Long expireTime = redisService.redisTemplate.getExpire("train" + customerId + "o" + orderNumber);
        TrainOrder trainOrder = trainOrderMapper.queryTrainOrder(customerId, orderNumber);
        cashier.setTrainnumber(trainOrder.getTrainnumber());
        cashier.setStatus(trainOrder.getStatus());
        cashier.setDeparturestationname(trainOrder.getDeparturestationname());
        cashier.setArrivalstationname(trainOrder.getArrivalstationname());
        cashier.setTraveldate(trainOrder.getTraveldate());
        cashier.setDeparturetime(trainOrder.getDeparturetime());
        cashier.setArrivaltime(trainOrder.getArrivaltime());
        cashier.setPayamount(trainOrder.getPayamount());
        cashier.setAddDay(trainOrder.getAddday());
        if (expireTime != null && expireTime > 0) {
//            Map<String, Object> map = new HashMap<>();
//            map.put("businessType", businessType);
            List<PayTypeApi> payTypes = payService.queryPayType(businessType);
            for (PayTypeApi payType : payTypes) {
                PayTypeVo typeVo = new PayTypeVo();
                typeVo.setPayId(payType.getPayId());
                typeVo.setPayName(payType.getPayName());
                typeVo.setPayType(payType.getPayType());
                typeVo.setPayInfo(payType.getPayInfo());
                cashier.getPayType().add(typeVo);
            }
            cashier.setExpiredTime(String.valueOf(expireTime));
        } else {
            cashier.setExpiredTime("订单已超时！");
        }
        return cashier;
    }

    //微信小程序支付
    @Override
    public Map<String, Object> wechatPay(Long customerId, String openId, String orderNumber, BigDecimal amount) throws Exception {
        TrainOrder trainOrder = trainOrderMapper.queryTrainOrder(customerId, orderNumber);

        if (amount != null && amount.compareTo(new BigDecimal(0)) > 0){
            trainOrder.setPayamount(trainOrder.getPayamount().subtract(amount));

            trainOrder.setDepositAmount(amount);
            int i = trainOrderMapper.updateTrainOrder(trainOrder);
            if (i <= 0){
                throw new Exception("修改订单预留款失败");
            }

            DepositBusinessApi depositBusiness = new DepositBusinessApi();
            depositBusiness.setRemark("微信小程序支付");
            depositBusiness.setState("false");
            depositBusiness.setBusinessType(EmHelper.businessType.TRAIN.getValue());
            depositBusiness.setOperatorId(10l);
            depositBusiness.setOrdersourceid("App");
            depositBusiness.setCustomerId(customerId);
            depositBusiness.setDetailamount(amount);
            depositBusiness.setChangetype(2l);
            depositBusiness.setLockState("false");
            depositBusiness.setOrderId(trainOrder.getOrderid());
            depositBusiness.setDrawState("false");
            Long aLong = remoteCustomerService.addReserveMoney(depositBusiness);
            if (aLong <= 0){
                throw new Exception("添加预留款失败");
            }

            Map<String, Object> map = new HashMap<>();
            map.put("id", aLong);
            map.put("remark", "微信小程序支付");
            boolean b = remoteCustomerService.manageAudit(map);
            if (!b){
                throw new Exception("审核失败， 请进行人工审核");
            }
        }

//        if (trainOrder.getPayamount().compareTo(new BigDecimal(0)) == 0){
//            Map<String, Object> wechatJSAPIPayParam = new HashMap<>();
//            wechatJSAPIPayParam.put("");
//            return
//        }

        String notifyUrl = "/train/callback/wechatPayCallback";
        R<Map> wechatJSAPIPayParam = payService.getWechatJSAPIPayParam(openId, trainOrder.getPayamount(), orderNumber, notifyUrl);
        if (wechatJSAPIPayParam.getCode() == 200) {
            return wechatJSAPIPayParam.getData();
        }
        return null;
    }

    //改签微信小程序支付
    @Override
    public Map<String, Object> changeWechatPay(String openId, String orderNumber, BigDecimal amount, String type) throws Exception {
        Map<String, Object> map = new HashMap<>();
        TrainOrder trainOrder = trainOrderMapper.selectTrainOrderById(Long.valueOf(orderNumber));
        List<TrainOrderRefundrecord> trainOrderRefundrecords = trainOrderRefundrecordService.queryTrainOrderRefundrecordList(Long.valueOf(orderNumber), FlightOrderChangeConstants.change.getValue());
        BigDecimal count = new BigDecimal(trainOrderRefundrecords.get(0).getDifferencePrice());
        if (amount != null && amount.compareTo(new BigDecimal(0)) > 0){
            count = count.subtract(amount);
            if (trainOrder.getDepositAmount().compareTo(new BigDecimal(0)) <= 0){
                trainOrder.setDepositAmount(amount);
            }
            else {
                trainOrder.setDepositAmount(trainOrder.getDepositAmount().add(amount));
            }
            int i = trainOrderMapper.updateTrainOrder(trainOrder);
            if (i <= 0){
                throw new Exception("修改订单失败");
            }
        }

        TrConfirmChangeRequest request = new TrConfirmChangeRequest();
        request.isasync = "Y";
        request.transactionid = trainOrder.getOrderpartnernumber();
        request.orderid = trainOrderRefundrecords.get(0).getMerchantOrderId();
        request.reqtoken = trainOrderRefundrecords.get(0).getReqToken();
        if (count.toString().equals("0")) {
            TrConfirmChangeResponse response = trainTickets.confirmChange(request);
            if (response.success) {
                map.put("errCode", "SUCCESS");
                map.put("errMsg", "改签申请成功");
                trainOrder.setStatus(TrainOrderEnum.changeTicketSuccess.getValue());
                trainOrderMapper.updateTrainOrder(trainOrder);
            } else {
                map.put("errCode", "FALSE");
                map.put("errMsg", "改签申请失败");
                trainOrder.setStatus(TrainOrderEnum.changeTicketFail.getValue());
                trainOrderMapper.updateTrainOrder(trainOrder);
            }
            return map;
        } else if (Float.parseFloat(count.toString()) < 0) {
            TrConfirmChangeResponse response = trainTickets.confirmChange(request);
            if (response.success) {
                map.put("errCode", "SUCCESS");
                map.put("errMsg", "改签申请成功");
                trainOrder.setStatus(TrainOrderEnum.changeTicketSuccess.getValue());
                trainOrderMapper.updateTrainOrder(trainOrder);
            } else {
                map.put("errCode", "FALSE");
                map.put("errMsg", "改签申请失败");
                trainOrder.setStatus(TrainOrderEnum.changeTicketFail.getValue());
                trainOrderMapper.updateTrainOrder(trainOrder);
            }
            return map;
        } else if (Float.parseFloat(count.toString()) > 0) {
            String notifyUrl = "/train/callback/changeWechatPayCallback";

            if (amount != null && amount.compareTo(new BigDecimal(0)) > 0){
                DepositBusinessApi depositBusiness = new DepositBusinessApi();
                depositBusiness.setOperatorId(10l);
                depositBusiness.setRemark("改签微信小程序支付");
                depositBusiness.setState("false");
                depositBusiness.setBusinessType(EmHelper.businessType.TRAIN.getValue());
                depositBusiness.setOrdersourceid(type);
                depositBusiness.setCustomerId(trainOrder.getJsjid());
                depositBusiness.setDetailamount(amount);
                depositBusiness.setChangetype(2l);
                depositBusiness.setLockState("false");
                depositBusiness.setOrderId(trainOrder.getOrderid());
                depositBusiness.setDrawState("false");
                Long aLong = remoteCustomerService.addReserveMoney(depositBusiness);
                if (aLong <= 0){
                    throw new Exception("添加预留款记录失败");
                }

                Map<String, Object> auditMap = new HashMap<>();
                auditMap.put("id", aLong);
                auditMap.put("remark", "改签微信小程序支付");
                boolean b = remoteCustomerService.manageAudit(auditMap);
                if (!b){
                    throw new Exception("审核失败，请进行人工审核");
                }
            }

            R<Map> wechatJSAPIPayParam = payService.getWechatJSAPIPayParam(openId, count, orderNumber, notifyUrl);
            if (wechatJSAPIPayParam.getCode() == 200) {
                trainOrderRefundrecords.forEach(item -> {
                    item.setPaymentOrderStatus(FlightOrderConstants.payd.toString());
                    item.setOrderStatus(FlightOrderConstants.payd.toString());
                    item.setChangeType("change");
                    trainOrderRefundrecordService.updateByOrderItemId(item);
                });
                return wechatJSAPIPayParam.getData();
            } else {
                trainOrderRefundrecords.forEach(item -> {
                    item.setPaymentOrderStatus(FlightOrderConstants.failPay.toString());
                    item.setOrderStatus(FlightOrderConstants.failPay.toString());
                    item.setChangeType("change");
                    trainOrderRefundrecordService.updateByOrderItemId(item);
                });
            }
        }
        return null;
    }

    @Override
    public TrainOrder selectTrainOrderByOrderId(String orderNumber) {
        return trainOrderMapper.selectTrainOrderByOrderId(orderNumber);
    }

    /**
     * 查询会员火车票订单列表
     * */
    @Override
    public List<TrainOrder> selectTrainOrderNum(Long customerId) throws Exception {
        List<CustomerCard> customerCards = remoteCustomerService.queryCardIdByCustomerId(customerId);//会员 卡号

        for (com.ktgj.customer.api.domain.CustomerCard customerCard : customerCards) {
            if (customerCard.getCardId() != null && customerCard.getCardId() != 0){
                Map<String, Object> map = new HashMap<>();
                map.put("cardId", customerCard.getCardId());
                Card card = remoteCustomerService.cardInfo(map);
                if (card != null){
                    customerCard.setCardLevel(card.getCardLevel());
                }
                else {
                    throw new Exception("无效的会员卡");
                }
            }
            else {
                throw new Exception("会员卡没有关联卡id");
            }
        }

        customerCards.sort((y, x) -> Double.compare(y.getCardLevel(), x.getCardLevel()));
        com.ktgj.customer.api.domain.CustomerCard customerCardR = customerCards.get(0);

        String cardNumber = customerCardR.getCardCode();

        List<TrainOrder> trainOrders = trainOrderMapper.selectTrainOrderNum(cardNumber);
        return trainOrders;
    }

    //火车票订单列表（CRM）
    @Override
    public List<TrainOrderCRM> trainOrder(TrainCRMOrder order) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        StringBuilder builder = new StringBuilder();
        if (order.getEndCreateTime() != null && order.getEndCreateTime() != "") {
            builder.append(order.getEndCreateTime());
            builder.append(" 23:59:59");
            order.setEndCreateTime(builder.toString());
        }
        if (order.getCustomerCard() != null && order.getCustomerCard() != "") {
            CustomerCard customerCard = remoteCustomerService.selectCustomerCard(order.getCustomerCard());
            order.setCustomerCard(String.valueOf(customerCard.getCustomerId()));
        }
        List<TrainOrderCRM> trainOrder = trainOrderMapper.trainOrder(order);
        for (TrainOrderCRM orderCRM : trainOrder) {
            List<TrainOrderItemCRM> itemCRMS = trainOrderItemService.trainOrderItem(Long.valueOf(orderCRM.getOrderid()));
            orderCRM.setTrainOrderItem(itemCRMS);

            if (orderCRM.getCreateTime() != null){
                orderCRM.setTime(format.format(orderCRM.getCreateTime()));
            }
        }
        return trainOrder;
    }

    //请求改签
    @Override
    public TrainChangeOrder trainRequestChange(TrTicketChangesRequest request) {
        TrainOrder trainOrder = trainOrderMapper.selectTrainOrderById(Long.valueOf(request.trainOrderId));
        //request.orderid = trainOrder.getMerchantOrderId();
        request.transactionid = trainOrder.getOrderpartnernumber();
        request.ordernumber = trainOrder.getOrder12306number();
        request.old_zwcode = trainOrder.getSeattype();
        request.isasync = "Y";
        //需要生成几位
        int n = 5;
        //最终生成的字符串
        String reqstr = "";
        for (int i = 0; i < n; i++) {
            reqstr = reqstr + (char) (Math.random() * 26 + 'a');
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("HHmmssSSS");
        String reqtime = dateFormat.format(new Date());
        request.reqtoken = reqstr + reqtime;
        request.orderid = trainOrder.getMerchantOrderId();
        request.orderItemId.forEach(item -> {
            TrainOrderitem trainOrderitem = trainOrderItemService.queryTrainOrderitemById(Long.valueOf(item));
            TicketInfo ticketinfo = new TicketInfo();
            ticketinfo.old_ticket_no = trainOrderitem.getTicketnumber();
            ticketinfo.passengersename = trainOrderitem.getGuestname();
            ticketinfo.passportseno = trainOrderitem.getIdnumber();
            if (trainOrderitem.getIdtype().equals("ID_CARD")) {
                ticketinfo.passporttypeseid = "1";
            } else if (trainOrderitem.getIdtype().equals("RPFHKMATR")) {
                ticketinfo.passporttypeseid = "2";
            } else if (trainOrderitem.getIdtype().equals("MTPFHKAMR")) {
                ticketinfo.passporttypeseid = "C";
            } else if (trainOrderitem.getIdtype().equals("MTPFTR")) {
                ticketinfo.passporttypeseid = "G";
            } else if (trainOrderitem.getIdtype().equals("PASSPORT")) {
                ticketinfo.passporttypeseid = "B";
            } else if (trainOrderitem.getIdtype().equals("PRICFF")) {
                ticketinfo.passporttypeseid = "H";
            }
            ticketinfo.piaotype = Math.toIntExact(trainOrderitem.getTickettype());

            request.ticketinfo.add(ticketinfo);
            TrainOrderRefundrecord refundrecord = new TrainOrderRefundrecord();
            refundrecord.setRecordid(System.currentTimeMillis() / 1000);
            refundrecord.setOrderid(Long.valueOf(request.trainOrderId));
            refundrecord.setOrderitemid(trainOrderitem.getOrderitemid());
            refundrecord.setName(trainOrderitem.getGuestname());
            refundrecord.setOldTicketNumber(trainOrderitem.getTicketnumber());
            refundrecord.setChangeType(FlightOrderChangeConstants.change.getValue());
            refundrecord.setDepartureStationName(request.from_station_name);
            refundrecord.setArrivalStationName(request.to_station_name);
            refundrecord.setDepartureTime(request.change_datetime.substring(11, 16));
            refundrecord.setTravelDate(request.change_datetime.substring(0, 10));
            refundrecord.setPaymentOrderStatus(TrainOrderEnum.unpaid.getValue());
            refundrecord.setOrderStatus(TrainOrderEnum.unpaid.getValue());
            refundrecord.setMerchantOrderId(request.orderid);
            refundrecord.setReqToken(request.reqtoken);
            refundrecord.setSeatType(request.change_zwcode);
            refundrecord.setTrainNumber(request.change_checi);
            refundrecord.setCreateTime(new Date());
            refundrecord.setOpemployeeid(1L);
            refundrecord.setSourceappid(trainOrder.getSourceappid());
            trainOrderRefundrecordService.insertTrainOrderRefundrecord(refundrecord);
        });
        TrTicketChangesResponse response = trainTickets.trainRequestChange(request);
        TrainChangeOrder changeOrder = new TrainChangeOrder();
        if (response.success) {
            trainOrder.setStatus(TrainOrderEnum.changeTicket.getValue());
            trainOrderMapper.updateTrainOrder(trainOrder);
            String str = "";
            while (str.equals("")) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (redisService.getCacheObject(request.reqtoken) != null) {
                    str = redisService.getCacheObject(request.reqtoken).toString();
                    redisService.deleteObject(request.reqtoken);
                }
            }
            List<TrainOrderRefundrecord> refundrecord = trainOrderRefundrecordService.queryTrainOrderRefundrecord(request.orderid);
            refundrecord.forEach(item -> {
                TrainChangeOrderTicket orderTicket = new TrainChangeOrderTicket();
                BeanUtils.copyProperties(item, changeOrder);
                TrainOrderitem trainOrderitem = trainOrderItemService.selectTrainOrderitemById(item.getOrderitemid());
                orderTicket.setName(trainOrderitem.getGuestname());
                orderTicket.setIdnumber(trainOrderitem.getIdnumber());
                orderTicket.setIdtype(trainOrderitem.getIdtype());
                orderTicket.setTickettype(trainOrderitem.getTickettype());
                BeanUtils.copyProperties(item, orderTicket);
                changeOrder.getOrderTickets().add(orderTicket);
            });
            changeOrder.setSuccess(true);
            changeOrder.setMsg(response.msg);
            changeOrder.setOrderid(String.valueOf(refundrecord.get(0).getOrderid()));
        } else {
            changeOrder.setSuccess(false);
            changeOrder.setMsg(response.msg);
        }
        return changeOrder;
    }

    //取消改签
    @Override
    public TrCancelChangeResponse trainCancelChange(String orderId) {
        TrCancelChangeRequest request = new TrCancelChangeRequest();
        TrainOrder trainOrder = trainOrderMapper.selectTrainOrderById(Long.valueOf(orderId));
        List<TrainOrderRefundrecord> trainOrderRefundrecords = trainOrderRefundrecordService.queryTrainOrderRefundrecordList(Long.valueOf(orderId), FlightOrderChangeConstants.change.getValue());
        request.orderid = trainOrderRefundrecords.get(0).getMerchantOrderId();
        request.reqtoken = trainOrderRefundrecords.get(0).getReqToken();
        request.transactionid = trainOrder.getOrderpartnernumber();
        TrCancelChangeResponse response = trainTickets.trainCancelChange(request);
        if (response.success) {
            trainOrder.setStatus(FlightOrderConstants.ticketing.getValue());
            trainOrderRefundrecords.forEach(item -> {
                item.setPaymentOrderStatus(FlightOrderConstants.cancelled.toString());
                item.setOrderStatus(FlightOrderConstants.cancelled.toString());
                item.setChangeType("change");
                trainOrderRefundrecordService.updateByOrderItemId(item);
            });
            trainOrderMapper.updateTrainOrder(trainOrder);
        }
        return response;
    }

    //改签支付
    @Override
    public UnionPayQRCodeResponseApi trainRequestChangeQRCode(HttpServletRequest servletRequest, String billNo, BigDecimal amount, String type) throws Exception {
        UnionPayQRCodeResponseApi qrCode = new UnionPayQRCodeResponseApi();
        TrainOrder trainOrder = trainOrderMapper.selectTrainOrderById(Long.valueOf(billNo));
        List<TrainOrderRefundrecord> trainOrderRefundrecords = trainOrderRefundrecordService.queryTrainOrderRefundrecordList(Long.valueOf(billNo), FlightOrderChangeConstants.change.getValue());

        if (amount != null && amount.compareTo(new BigDecimal(0)) > 0){
            trainOrderRefundrecords.get(0).setDifferencePrice((new BigDecimal(trainOrderRefundrecords.get(0).getDifferencePrice()).subtract(amount)).toString());
        }


        TrConfirmChangeRequest request = new TrConfirmChangeRequest();
        request.isasync = "Y";
        request.transactionid = trainOrder.getOrderpartnernumber();
        request.orderid = trainOrderRefundrecords.get(0).getMerchantOrderId();
        request.reqtoken = trainOrderRefundrecords.get(0).getReqToken();
        if (trainOrderRefundrecords.get(0).getDifferencePrice().equals("0")) {
            TrConfirmChangeResponse response = trainTickets.confirmChange(request);
            if (response.success) {
                qrCode.setErrCode("SUCCESS");
                qrCode.setErrMsg("改签申请成功");
                trainOrder.setStatus(TrainOrderEnum.changeTicketSuccess.getValue());
                trainOrderMapper.updateTrainOrder(trainOrder);
            } else {
                qrCode.setErrCode("FALSE");
                qrCode.setErrMsg("改签申请失败");
                trainOrder.setStatus(TrainOrderEnum.changeTicketFail.getValue());
                trainOrderMapper.updateTrainOrder(trainOrder);
            }
        } else if (Float.parseFloat(trainOrderRefundrecords.get(0).getDifferencePrice()) < 0) {
            TrConfirmChangeResponse response = trainTickets.confirmChange(request);
            if (response.success) {
                qrCode.setErrCode("SUCCESS");
                qrCode.setErrMsg("改签申请成功");
                trainOrder.setStatus(TrainOrderEnum.changeTicketSuccess.getValue());
                trainOrderMapper.updateTrainOrder(trainOrder);
            } else {
                qrCode.setErrCode("FALSE");
                qrCode.setErrMsg("改签申请失败");
                trainOrder.setStatus(TrainOrderEnum.changeTicketFail.getValue());
                trainOrderMapper.updateTrainOrder(trainOrder);
            }
        } else if (Float.parseFloat(trainOrderRefundrecords.get(0).getDifferencePrice()) > 0) {

            if (amount.compareTo(new BigDecimal(0)) > 0){
                DepositBusinessApi depositBusiness = new DepositBusinessApi();

                String token = servletRequest.getHeader("token");
                Employee employee = remoteCustomerService.getLoginEmployeeByToken(token).getData();
                if (employee == null){
                    throw new Exception("登陆已过期");
                }
                depositBusiness.setOperatorId(employee.getEmployeeId());
                depositBusiness.setRemark("火车票改签支付");
                depositBusiness.setState("false");
                depositBusiness.setBusinessType(EmHelper.businessType.TRAIN.getValue());
                depositBusiness.setOrdersourceid(type);
                depositBusiness.setCustomerId(trainOrder.getJsjid());
                depositBusiness.setDetailamount(amount);
                depositBusiness.setChangetype(2l);
                depositBusiness.setLockState("false");
                depositBusiness.setOrderId(trainOrder.getOrderid());
                depositBusiness.setDrawState("false");
                Long aLong = remoteCustomerService.addReserveMoney(depositBusiness);
                if (aLong > 0){
                    throw new Exception("添加预留款记录失败");
                }

                Map<String, Object> map = new HashMap<>();
                map.put("id", aLong);
                map.put("remark", "火车票改签支付");
                boolean b = remoteCustomerService.manageAudit(map);
                if (!b){
                    throw new Exception("审核失败，请进行人工审核");
                }
            }

            if (new BigDecimal(trainOrderRefundrecords.get(0).getDifferencePrice()).compareTo(new BigDecimal(0)) > 0){
                Map<String, String> QRMap = new HashMap<>();
                QRMap.put("billNo", "5676" + billNo);
                QRMap.put("totalAmount", String.valueOf(new BigDecimal(trainOrderRefundrecords.get(0).getDifferencePrice()).multiply(new BigDecimal(100)).longValue()));
                QRMap.put("notifyUrl", "http://106.38.39.137:8080/train/callback/trainChangeVoicePayCallback");
                qrCode = payService.getQRCode(QRMap);
                if (qrCode.getErrCode().equals("SUCCESS")) {
                    trainOrderRefundrecords.forEach(item -> {
                        item.setPaymentOrderStatus(FlightOrderConstants.payd.toString());
                        item.setOrderStatus(FlightOrderConstants.payd.toString());
                        item.setChangeType("change");
                        trainOrderRefundrecordService.updateByOrderItemId(item);
                    });
                } else {
                    trainOrderRefundrecords.forEach(item -> {
                        item.setPaymentOrderStatus(FlightOrderConstants.failPay.toString());
                        item.setOrderStatus(FlightOrderConstants.failPay.toString());
                        item.setChangeType("change");
                        trainOrderRefundrecordService.updateByOrderItemId(item);
                    });
                }
            }
        }
        return qrCode;
    }

    @Override
    public int queryTrainOrderNumber(Long customerId) {
        return trainOrderMapper.queryTrainOrderNumber(customerId);
    }

    //支付宝支付
    @Override
    public String aliPay(String orderNumber) {
        TrainOrder trainOrder = trainOrderMapper.selectTrainOrderByOrderId(orderNumber);
        Map<String, Object> map = new HashMap<>();
        map.put("payMoney", trainOrder.getPayamount());
        map.put("orderNumber", orderNumber);
        map.put("notifyUrl", "http://106.38.39.137:8080/train/callback/aliPayCallback");
        String postAliPayParam = payService.postAliPayParam(map);
        if (postAliPayParam != null && !postAliPayParam.equals("")){
            return postAliPayParam;
        }
        else {
            return null;
        }
    }

    //火车票银行卡支付
    @Override
    public String bankCardPay(HttpServletRequest request, TrainBankCardPay bankCardPay) throws Exception{
        TrainOrder trainOrder = trainOrderService.selectTrainOrderByOrderId(bankCardPay.jsjOrderId);

        if (bankCardPay.amount != null && bankCardPay.amount.compareTo(new BigDecimal(0)) > 0){

            trainOrder.setDepositAmount(bankCardPay.amount);
            int i = trainOrderMapper.updateByCallback(trainOrder);
            if (i <= 0){
                throw new Exception("修改火车票订单失败");
            }

            trainOrder.setPayamount(trainOrder.getPayamount().subtract(bankCardPay.amount));

            DepositBusinessApi depositBusiness = new DepositBusinessApi();
            depositBusiness.setRemark("火车票银行卡支付");
            depositBusiness.setState("false");
            depositBusiness.setBusinessType(EmHelper.businessType.TRAIN.getValue());

            String token = request.getHeader("token");
            Employee employee = remoteCustomerService.getLoginEmployeeByToken(token).getData();
            if (employee == null){
                throw new Exception("登录已过期");
            }

            depositBusiness.setOperatorId(employee.getEmployeeId());
            depositBusiness.setOrdersourceid(bankCardPay.source);
            depositBusiness.setCustomerId(bankCardPay.customerId);
            depositBusiness.setDetailamount(bankCardPay.amount);
            depositBusiness.setChangetype(2l);
            depositBusiness.setLockState("true");
            depositBusiness.setCreateTime(new Date());
            depositBusiness.setOrderId(Long.valueOf(bankCardPay.jsjOrderId));
            depositBusiness.setDrawState("false");
            Long aLong = remoteCustomerService.addReserveMoney(depositBusiness);
            if (aLong <= 0){
                throw new Exception("添加预留款记录失败");
            }

            Map<String, Object> map = new HashMap<>();
            map.put("id", aLong);
            map.put("remark", "火车票银行卡支付");
            boolean b = remoteCustomerService.manageAudit(map);
            if (!b){
                throw new Exception("支付审核失败，请联系工作人员进行人工审核");
            }

            if (trainOrder.getPayamount().compareTo(new BigDecimal(0)) <= 0){

                TrOutTicketRequest ticketRequest = new TrOutTicketRequest();
                ticketRequest.transactionid = trainOrder.getOrderpartnernumber();
                ticketRequest.orderid = trainOrder.getMerchantOrderId();

                TrainOrder order = new TrainOrder();
                order.setOrderid(trainOrder.getOrderid());
                order.setPaymentorderstatus(CustomerConstants.payd.getValue());
                order.setStatus(CustomerConstants.payd.getValue());
                if (bankCardPay.Cvv2 != null && bankCardPay.Cvv2 != 0)
                    order.setPayType(BusinessTypeConstants.BankCredit.getValue());
                else
                    order.setPayType(BusinessTypeConstants.BankDebit.getValue());
                Long billNo = System.currentTimeMillis() / 1000;
                order.setBillNo(billNo.toString());
                trainOrderService.updateTrainOrder(order);

                TrainOrderitem orderitem = new TrainOrderitem();
                orderitem.setOrderid(trainOrder.getOrderid());
                orderitem.setStatus(CustomerConstants.payd.getValue());
                trainOrderItemService.updateByOrderId(orderitem);

                TrOutTicketResponse response = trainTickets.outTicket(ticketRequest);
                if (response.success) {
                    TrainOrder train = new TrainOrder();
                    train.setOrderid(trainOrder.getOrderid());
                    train.setStatus(FlightOrderConstants.ticketing.getValue());
                    trainOrderService.updateTrainOrder(train);
                    List<TrainOrderitem> trainOrderitems = trainOrderitemMapper.selectTrainOrderitemByOrderId(trainOrder.getOrderid());
                    if (trainOrderitems != null && trainOrderitems.size() > 0)
                        trainOrderAssist(trainOrder, trainOrderitems);
                }
                System.out.println("确认出票：" + response);

                return "支付成功";
            }
        }

        CustomerApi customer = new CustomerApi();
        customer.setCustCertificateNo(bankCardPay.custCertificateNo);
        customer.setContractPhoneOne(bankCardPay.contractPhoneOne);
        //银行卡信息
        BankCardApi card = new BankCardApi();
        card.setCardNumber(bankCardPay.cardNumber);
        card.setCardholder(bankCardPay.cardholder);

        Map<String, Object> map = new HashMap<>();
        map.put("cardNumber", bankCardPay.cardNumber);
        String backCard = remoteCustomerService.backCard(map);

        card.bankCode = backCard + "CREDIT";
        card.setCreditCardTime(bankCardPay.creditCardTime);
        card.setCvv2(bankCardPay.Cvv2);

        BankPayInfoApi bankPayInfoApi = new BankPayInfoApi();
        bankPayInfoApi.setJsjOrderId(bankCardPay.jsjOrderId);
        bankPayInfoApi.setMoneyAmout(String.valueOf(trainOrder.getPayamount()));
        bankPayInfoApi.setCustomer(customer);
        bankPayInfoApi.setCard(card);
        bankPayInfoApi.setPayType(trainOrder.getSourceappid());

        YeeBaoResultApi yeeBaoResultApi;
        if (bankCardPay.type.equals("creditcard")){
            yeeBaoResultApi = payService.CreditSale(bankPayInfoApi);
        }
        else if (bankCardPay.type.equals("debitcard")){
            yeeBaoResultApi = payService.DebitSale(bankPayInfoApi);
        }
        else {
            throw new Exception("支付类型不明确");
        }

        System.out.println("订单号：" + bankCardPay.jsjOrderId);
        System.out.println("交易流水号：" + yeeBaoResultApi.getTrxId());

        if (yeeBaoResultApi.getCode().equals("1")){
            if (bankCardPay.jsjOrderId != null) {
                TrOutTicketRequest ticketRequest = new TrOutTicketRequest();
                ticketRequest.transactionid = trainOrder.getOrderpartnernumber();
                ticketRequest.orderid = trainOrder.getMerchantOrderId();

                TrainOrder order = new TrainOrder();
                order.setOrderid(trainOrder.getOrderid());
                order.setPaymentorderstatus(CustomerConstants.payd.getValue());
                order.setStatus(CustomerConstants.payd.getValue());
                if (bankCardPay.Cvv2 != null && bankCardPay.Cvv2 != 0)
                    order.setPayType(BusinessTypeConstants.BankCredit.getValue());
                else
                    order.setPayType(BusinessTypeConstants.BankDebit.getValue());
                order.setBillNo(yeeBaoResultApi.getTrxId());
                trainOrderService.updateTrainOrder(order);

                TrainOrderitem orderitem = new TrainOrderitem();
                orderitem.setOrderid(trainOrder.getOrderid());
                orderitem.setStatus(CustomerConstants.payd.getValue());
                trainOrderItemService.updateByOrderId(orderitem);

                TrainOrderOperation orderOperation = new TrainOrderOperation();
                orderOperation.setOperationname("支付成功");
                orderOperation.setOrderid(trainOrder.getOrderid());
                orderOperation.setOpemployeeid(1L);
                orderOperation.setOpemployeename("系统服务");
                orderOperation.setCreateTime(new Date());
                trainOrderOperationMapper.insertTrainOrderOperation(orderOperation);

                TrOutTicketResponse response = trainTickets.outTicket(ticketRequest);
                if (response.success) {
                    TrainOrder train = new TrainOrder();
                    train.setOrderid(trainOrder.getOrderid());
                    train.setStatus(FlightOrderConstants.ticketing.getValue());
                    trainOrderService.updateTrainOrder(train);
                    List<TrainOrderitem> trainOrderitems = trainOrderitemMapper.selectTrainOrderitemByOrderId(trainOrder.getOrderid());
                    if (trainOrderitems != null && trainOrderitems.size() > 0)
                        trainOrderAssist(trainOrder, trainOrderitems);
                }
                System.out.println("确认出票：" + response);
            }
            return "支付成功";
        }
        else {
            return yeeBaoResultApi.getErrorMsg();
        }
    }

    private void trainOrderAssist(TrainOrder trainOrder, List<TrainOrderitem> trainOrderitems) {
        for (TrainOrderitem trainOrderitem : trainOrderitems) {
            List<TrainOrderAssist> trainOrderAssists = trainOrderAssistService.queryAssistByorderItemId(trainOrderitem.getOrderitemid());
            if (trainOrderAssists != null && trainOrderAssists.size() > 0) {
                for (TrainOrderAssist orderAssist : trainOrderAssists) {
                    if (orderAssist.getInsType() != null && orderAssist.getInsType().equals("insurance")) {
                        ProductVoApi product = new ProductVoApi();
                        product.id = orderAssist.getAssistProductId();
                        product.customerId = trainOrder.getJsjid();
                        product.orderNum = String.valueOf(trainOrder.getOrderid() + orderAssist.getId());
                        product.paymentChannel = trainOrder.getPayType();
                        product.relation = "01";
                        //证件类型
                        product.insuredIdType = trainOrderitem.getIdtype();

                        product.flightNo = trainOrder.getTrainnumber();
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        String departureTime = trainOrder.getTraveldate() + " " + trainOrder.getDeparturetime();
                        String[] departure = departureTime.split(" ");
                        product.flightDate = departureTime;
                        product.flightTime = departure[1];
                        product.arriveTime = trainOrder.getArrivaltime();
                        product.insuredName = trainOrderitem.getGuestname();
                        product.insuredId = trainOrderitem.getIdnumber();
                        product.insuredPhone = trainOrderitem.getMobile();
                        String guestBirthday = "";
                        if (trainOrderitem.getBirthday() != null)
                            guestBirthday = dateFormat.format(trainOrderitem.getBirthday());
                        if (!guestBirthday.equals(""))
                            product.beInsuredBirthday = guestBirthday.split(" ")[0];
                        product.ticketNo = trainOrderitem.getTicketnumber();
                        product.flightIndex = "1";
                        product.depCity = trainOrder.getDeparturestationcode();
                        product.arrCity = trainOrder.getArrivalstationcode();
                        product.insuranceType = 5;
                        product.orderSource = BusinessTypeConstants.train.getValue();
                        InsuranceReturnVoApi recordBack = remoteCustomerService.insertInsuranceRecordBack(product);
                        if (recordBack != null) {
                            if (recordBack.isSuccess()) {
                                orderAssist.setStatus("normal");
                                trainOrderAssistService.updateTrainOrderAssist(orderAssist);
                            } else {
                                orderAssist.setStatus("fail");
                                trainOrderAssistService.updateTrainOrderAssist(orderAssist);
                            }
                        } else {
                            orderAssist.setStatus("fail");
                            trainOrderAssistService.updateTrainOrderAssist(orderAssist);
                        }
                    } else if (orderAssist.getInsType() != null && orderAssist.getInsType().equals("conpon")) {
                        R<AssistProductApi> productApiR = remoteCustomerService.queryAssistProduct(orderAssist.getAssistProductId());
                        if (productApiR.getCode() == 200 && productApiR.getData() != null) {
                            R<Coupon> couponR = remoteCustomerService.couponById(productApiR.getData().getProductTypeid());
                            CustomerRightdetail customerRightdetai = new CustomerRightdetail();
                            customerRightdetai.setCustomerId(trainOrder.getJsjid());
                            customerRightdetai.setRightdetailId(couponR.getData().getCouponId());
                            customerRightdetai.setRightdetailName(couponR.getData().getCouponName());
                            customerRightdetai.setCouponMoney(couponR.getData().getCouponPrice());
                            customerRightdetai.setValidDate(new Date());
                            Calendar calendar = new GregorianCalendar();
                            calendar.setTime(new Date());
                            calendar.add(Calendar.YEAR, 1);
                            customerRightdetai.setInvalidDate(calendar.getTime());
                            customerRightdetai.setCreateEmployeeId(1L);
                            customerRightdetai.setCreateTime(new Date());
                            customerRightdetai.setRightdetailSource(CustomerConstants.rightSourcePack.getValue());
                            customerRightdetai.setRightdetailType(CustomerConstants.rightTypeCoupon.getValue());
                            customerRightdetai.setRightdetailTypeid(couponR.getData().getCouponId());
                            customerRightdetai.setRightdetailState(CustomerConstants.unexecuted.getValue());
                            remoteCustomerService.addCustomerRightdetail(customerRightdetai);
                        }
                    }
                }
            }
        }
    }

    //改签火车票银行卡支付
    @Override
    public String changeBankCardPay(HttpServletRequest servletRequestrequest, TrainBankCardPay bankCardPay) throws Exception {
        TrainOrder trainOrder = trainOrderMapper.selectTrainOrderById(Long.valueOf(bankCardPay.jsjOrderId));
        if (bankCardPay.amount != null && bankCardPay.amount.compareTo(new BigDecimal(0)) > 0){
            trainOrder.setPayamount(trainOrder.getPayamount().subtract(bankCardPay.amount));
        }

        List<TrainOrderRefundrecord> trainOrderRefundrecords = trainOrderRefundrecordService.queryTrainOrderRefundrecordList(Long.valueOf(bankCardPay.jsjOrderId), FlightOrderChangeConstants.change.getValue());
        TrConfirmChangeRequest request = new TrConfirmChangeRequest();
        request.isasync = "Y";
        request.transactionid = trainOrder.getOrderpartnernumber();
        request.orderid = trainOrderRefundrecords.get(0).getMerchantOrderId();
        request.reqtoken = trainOrderRefundrecords.get(0).getReqToken();
        if (trainOrderRefundrecords.get(0).getDifferencePrice().equals("0")) {
            TrConfirmChangeResponse response = trainTickets.confirmChange(request);
            if (response.success) {
                return "改签申请成功";
            } else {
                return response.msg;
            }
        } else if (Float.parseFloat(trainOrderRefundrecords.get(0).getDifferencePrice()) < 0) {
            TrConfirmChangeResponse response = trainTickets.confirmChange(request);
            if (response.success) {
                return "改签申请成功";
            } else {
                return response.msg;
            }
        } else if (Float.parseFloat(trainOrderRefundrecords.get(0).getDifferencePrice()) > 0) {

            if (bankCardPay.amount != null && bankCardPay.amount.compareTo(new BigDecimal(0)) > 0){

                for (TrainOrderRefundrecord trainOrderRefundrecord : trainOrderRefundrecords) {
                    trainOrderRefundrecord.setAmount(bankCardPay.amount);
                    int i = trainOrderRefundrecordMapper.updateTrainOrderRefundrecord(trainOrderRefundrecord);
                    if (i <= 0){
                        throw new Exception("修改订单预留款失败" + trainOrderRefundrecord.getRecordid());
                    }
                }

                DepositBusinessApi depositBusiness = new DepositBusinessApi();
                depositBusiness.setRemark("火车票语音组合支付");
                depositBusiness.setState("false");
                depositBusiness.setBusinessType(EmHelper.businessType.TRAIN.getValue());

                String token = servletRequestrequest.getHeader("token");
                Employee employee = remoteCustomerService.getLoginEmployeeByToken(token).getData();
                if (employee == null){
                    throw new Exception("登录已过期");
                }

                depositBusiness.setOperatorId(employee.getEmployeeId());
                depositBusiness.setOrdersourceid(bankCardPay.source);
                depositBusiness.setCustomerId(bankCardPay.customerId);
                depositBusiness.setDetailamount(bankCardPay.amount);
                depositBusiness.setChangetype(2l);
                depositBusiness.setLockState("true");
                depositBusiness.setCreateTime(new Date());
                depositBusiness.setOrderId(Long.valueOf(bankCardPay.jsjOrderId));
                depositBusiness.setDrawState("false");
                Long aLong = remoteCustomerService.addReserveMoney(depositBusiness);
                if (aLong <= 0){
                    throw new Exception("添加预留款记录失败");
                }

                Map<String, Object> map = new HashMap<>();
                map.put("id", aLong);
                map.put("remark", "火车票语音支付");
                boolean b = remoteCustomerService.manageAudit(map);
                if (!b){
                    throw new Exception("支付审核失败，请进行人工审核");
                }

                if (trainOrder.getPayamount().compareTo(new BigDecimal(0)) <= 0){

                    trainOrderRefundrecords.forEach(item -> {
                        item.setOrderid(trainOrder.getOrderid());
                        if (bankCardPay.Cvv2 != null && bankCardPay.Cvv2 != 0)
                            item.setPayType(BusinessTypeConstants.BankCredit.getValue());
                        else
                            item.setPayType(BusinessTypeConstants.BankDebit.getValue());
                        Long billNo = System.currentTimeMillis() / 1000;
                        item.setBillNo(billNo.toString());
                        item.setAmount(bankCardPay.amount);
                        item.setChangeType("change");
                        trainOrderRefundrecordService.updateByOrderId(item);
                    });
                    if (bankCardPay.jsjOrderId != null) {
                        TrConfirmChangeResponse response = trainTickets.confirmChange(request);
                        if (response.success) {
                            return "改签申请成功";
                        }
                    }

                    return "支付成功";
                }
            }

            if (bankCardPay.amount != null && bankCardPay.amount.compareTo(new BigDecimal(0)) > 0){

            }

            CustomerApi customer = new CustomerApi();
            customer.setCustCertificateNo(bankCardPay.custCertificateNo);
            customer.setContractPhoneOne(bankCardPay.contractPhoneOne);
            //银行卡信息
            BankCardApi card = new BankCardApi();
            card.setCardNumber(bankCardPay.cardNumber);
            card.setCardholder(bankCardPay.cardholder);

            Map<String, Object> map = new HashMap<>();
            map.put("cardNumber", bankCardPay.cardNumber);
            String backCard = remoteCustomerService.backCard(map);

            card.bankCode = backCard + "CREDIT";
            card.setCreditCardTime(bankCardPay.creditCardTime);
            card.setCvv2(bankCardPay.Cvv2);

            BankPayInfoApi bankPayInfoApi = new BankPayInfoApi();
            bankPayInfoApi.setJsjOrderId(bankCardPay.jsjOrderId);
            bankPayInfoApi.setMoneyAmout(bankCardPay.moneyAmout);
            bankPayInfoApi.setCustomer(customer);
            bankPayInfoApi.setCard(card);
            bankPayInfoApi.setPayType(trainOrderRefundrecords.get(0).getSourceappid());

            YeeBaoResultApi yeeBaoResultApi;
            if (bankCardPay.type.equals("creditcard")){
                yeeBaoResultApi = payService.CreditSale(bankPayInfoApi);
            }
            else if (bankCardPay.type.equals("debitcard")){
                yeeBaoResultApi = payService.DebitSale(bankPayInfoApi);
            }
            else {
                throw new Exception("支付类型不明确");
            }

            if (yeeBaoResultApi.getCode().equals("1")){
                trainOrderRefundrecords.forEach(item -> {
                    item.setOrderid(trainOrder.getOrderid());
                    if (bankCardPay.Cvv2 != null && bankCardPay.Cvv2 != 0)
                        item.setPayType(BusinessTypeConstants.BankCredit.getValue());
                    else
                        item.setPayType(BusinessTypeConstants.BankDebit.getValue());
                    item.setBillNo(yeeBaoResultApi.getTrxId());
                    item.setAmount(bankCardPay.amount);
                    item.setChangeType("change");
                    trainOrderRefundrecordService.updateByOrderId(item);
                });
                TrainOrderOperation orderOperation = new TrainOrderOperation();
                orderOperation.setOperationname("支付成功");
                orderOperation.setOrderid(trainOrder.getOrderid());
                orderOperation.setOpemployeeid(1L);
                orderOperation.setOpemployeename("系统服务");
                orderOperation.setCreateTime(new Date());
                trainOrderOperationMapper.insertTrainOrderOperation(orderOperation);
                if (bankCardPay.jsjOrderId != null) {
                    TrConfirmChangeResponse response = trainTickets.confirmChange(request);
                    if (response.success) {
                        return "改签申请成功";
                    }
                }
            }
            else {
                return yeeBaoResultApi.getErrorMsg();
            }
        }
        return null;
    }

    //火车票语音支付
    @Override
    public String voice(HttpServletRequest request, TrainBankCardPay bankCardPay) throws Exception {
        TrainOrder trainOrder = trainOrderService.selectTrainOrderByOrderId(bankCardPay.jsjOrderId);

        if (bankCardPay.amount != null && bankCardPay.amount.compareTo(new BigDecimal(0)) > 0){

            trainOrder.setDepositAmount(bankCardPay.amount);
            int i = trainOrderMapper.updateByCallback(trainOrder);
            if (i <= 0){
                throw new Exception("修改火车票订单失败");
            }

            trainOrder.setPayamount(trainOrder.getPayamount().subtract(bankCardPay.amount));

            DepositBusinessApi depositBusiness = new DepositBusinessApi();
            depositBusiness.setRemark("火车票语音组合支付");
            depositBusiness.setState("false");
            depositBusiness.setBusinessType(EmHelper.businessType.TRAIN.getValue());

            String token = request.getHeader("token");
            Employee employee = remoteCustomerService.getLoginEmployeeByToken(token).getData();
            if (employee == null){
                throw new Exception("登录已过期");
            }

            depositBusiness.setOperatorId(employee.getEmployeeId());
            depositBusiness.setOrdersourceid(bankCardPay.source);
            depositBusiness.setCustomerId(bankCardPay.customerId);
            depositBusiness.setDetailamount(bankCardPay.amount);
            depositBusiness.setChangetype(2l);
            depositBusiness.setLockState("true");
            depositBusiness.setCreateTime(new Date());
            depositBusiness.setOrderId(Long.valueOf(bankCardPay.jsjOrderId));
            depositBusiness.setDrawState("false");
            Long aLong = remoteCustomerService.addReserveMoney(depositBusiness);
            if (aLong <= 0){
                throw new Exception("添加预留款记录失败");
            }

            Map<String, Object> map = new HashMap<>();
            map.put("id", aLong);
            map.put("remark", "火车票语音组合支付");
            boolean b = remoteCustomerService.manageAudit(map);
            if (!b){
                throw new Exception("支付审核失败，请联系工作人员进行人工审核");
            }

            if (trainOrder.getPayamount().compareTo(new BigDecimal(0)) == 0){

                trainOrder.setPaymentorderstatus(FlightOrderConstants.payd.toString());
                trainOrder.setStatus(FlightOrderConstants.payd.toString());
                trainOrderService.updateTrainOrder(trainOrder);

                TrOutTicketRequest ticketRequest = new TrOutTicketRequest();
                ticketRequest.transactionid = trainOrder.getOrderpartnernumber();
                ticketRequest.orderid = trainOrder.getMerchantOrderId();

                TrOutTicketResponse ticketResponse = trainTickets.outTicket(ticketRequest);
                if (ticketResponse.success) {
                    TrainOrder train = new TrainOrder();
                    train.setOrderid(trainOrder.getOrderid());
                    train.setStatus(FlightOrderConstants.ticketing.getValue());
                    trainOrderService.updateTrainOrder(train);
                }

                return "支付成功";
            }
        }

        Map<String, Object> voice = new HashMap<>();
        voice.put("mobileNumber", bankCardPay.contractPhoneOne);
        voice.put("bankCardNo", bankCardPay.cardNumber);
        voice.put("idCardNo", bankCardPay.custCertificateNo);
        voice.put("idCardName", bankCardPay.cardholder);
        voice.put("orderAmount", String.valueOf(trainOrder.getPayamount().multiply(new BigDecimal(100)).longValue()));
        voice.put("orderId", bankCardPay.jsjOrderId);
        voice.put("asynAddress", "http://106.38.39.137:8080/train/callback/voiceCallback");

        String voicePay = payService.voicePay(voice);

        String newVoicePay = "支付失败";
        if (voicePay != null){
            newVoicePay = voicePay.substring(0, voicePay.indexOf(","));
//                String voicePayNew = voicePay.substring(voicePay.indexOf(",") + 1);
            if (newVoicePay.equals("请注意来电")){
                return newVoicePay;
            }
            else {
                return null;
            }
        }
        else {
            return null;
        }
    }

    //订单列表app
    @Override
    public List<TrainOrderApp> orderApp(Long customerId, String status) {
        List<TrainOrderApp> orderApps = new ArrayList<>();
        List<TrainOrderApp> trainOrder = trainOrderMapper.orderApp(customerId);
        trainOrder.forEach(item -> {
            Date create = item.getCreateTime();
            Calendar cal = Calendar.getInstance();
            cal.setTime(create);
            cal.add(Calendar.MINUTE, 30);
            Date calDate = cal.getTime();
            Date date = new Date();

            long time = calDate.getTime();
            long dateTime = date.getTime();
            long expirationTime = (time - dateTime) / 1000;
            if (item.getStatus().equals("unpaid")) {
                item.setExpirationTime(String.valueOf(expirationTime));
            }
        });
        if (status.equals("")) {
            return trainOrder;
        } else if (status.equals("unpaid")) {
            trainOrder.forEach(item -> {
                TrainOrderApp trainOrderApp = new TrainOrderApp();
                if (item.getStatus().equals("unpaid")) {
                    BeanUtils.copyProperties(item, trainOrderApp);
                    orderApps.add(trainOrderApp);
                }
            });
            return orderApps;
        } else if (status.equals("ticketing")) {
            trainOrder.forEach(item -> {
                TrainOrderApp trainOrderApp = new TrainOrderApp();
                if (item.getStatus().equals("ticketing")) {
                    BeanUtils.copyProperties(item, trainOrderApp);
                    orderApps.add(trainOrderApp);
                }
            });
            return orderApps;
        } else if (status.equals("changeReturn")) {
            trainOrder.forEach(item -> {
                TrainOrderApp trainOrderApp = new TrainOrderApp();
                if (item.getStatus().equals("processing") || item.getStatus().equals("refundTicketSuccess") || item.getStatus().equals("changeTicket")
                        || item.getStatus().equals("changeTicketSuccess") || item.getStatus().equals("refundTicketFail") || item.getStatus().equals("changeTicketFail")) {
                    BeanUtils.copyProperties(item, trainOrderApp);
                    orderApps.add(trainOrderApp);
                }
            });
            return orderApps;
        }
        return null;
    }

    /**
     * 行程火车票订单
     * */
    @Override
    public JourneyTrainOrderVo journeyTrainOrder(Long orderid) {
        TrainOrder trainOrder = trainOrderMapper.journeyTrainOrder(orderid);
        JourneyTrainOrderVo journeyTrainOrderVo = new JourneyTrainOrderVo();
        journeyTrainOrderVo.setOrderId(trainOrder.getMerchantOrderId());
        journeyTrainOrderVo.setBusinessType(EmHelper.businessType.TRAIN.getValue());
        journeyTrainOrderVo.setActualPriceTotal(trainOrder.getPayamount().toString());
        if (trainOrder.getStatus().equals(TrainOrderEnum.cancelOrder.getValue())){
            journeyTrainOrderVo.setOrderStatusID("取消订单");
        }
        else if (trainOrder.getStatus().equals(TrainOrderEnum.paid.getValue()) || trainOrder.getStatus().equals(CustomerConstants.payd.getValue())){
            journeyTrainOrderVo.setOrderStatusID("已支付");
        }
        else if (trainOrder.getStatus().equals(TrainOrderEnum.changeTicketSuccess.getValue())){
            journeyTrainOrderVo.setOrderStatusID("改签成功");
        }
        else if (trainOrder.getStatus().equals(TrainOrderEnum.changeTicket.getValue())){
            journeyTrainOrderVo.setOrderStatusID("改签中");
        }
        else if (trainOrder.getStatus().equals(TrainOrderEnum.refundTicketSuccess.getValue())){
            journeyTrainOrderVo.setOrderStatusID("退票成功");
        }
        else if (trainOrder.getStatus().equals(FlightOrderConstants.ticketing.getValue())){
            journeyTrainOrderVo.setOrderStatusID("出票成功");
        }
        else {
            journeyTrainOrderVo.setOrderStatusID(trainOrder.getStatus());
        }
        journeyTrainOrderVo.setTrainnumber(trainOrder.getTrainnumber());
        journeyTrainOrderVo.setDeparturestationname(trainOrder.getDeparturestationname());
        journeyTrainOrderVo.setArrivalstationname(trainOrder.getArrivalstationname());
        journeyTrainOrderVo.setDeparturetime(trainOrder.getDeparturetime());
        journeyTrainOrderVo.setArrivaltime(trainOrder.getArrivaltime());
        journeyTrainOrderVo.setTraveldate(trainOrder.getTraveldate());
        return journeyTrainOrderVo;
    }

    /**
     * 订单号获取火车票订单信息
     * */
    @Override
    public TrainOrder orderNum(String orderNum) {
        TrainOrder trainOrder = trainOrderMapper.selectTrainOrderByOrderId(orderNum);
        return trainOrder;
    }

    /**
     * 火车票订单号获取会员信息
     * */
    @Override
    public CustomerTrain customerByTrainNum(String orderNum) {
        CustomerTrain customerTrain = new CustomerTrain();
        TrainOrder trainOrder = trainOrderMapper.selectTrainOrderByOrderId(orderNum);
        if (trainOrder != null){
            CustomerIdVoApi customerIdVoApi = new CustomerIdVoApi();
            customerIdVoApi.setCustomerId(trainOrder.getJsjid());
            customerIdVoApi = remoteCustomerService.customerIdApi(customerIdVoApi);
            if (customerIdVoApi != null){
                customerTrain.setId(customerIdVoApi.getCustomerId());
                customerTrain.setPhone(customerIdVoApi.getCustomerPhone());
                customerTrain.setName(customerIdVoApi.getCustomerName());
                customerTrain.setIdCard(customerIdVoApi.getLicenseNum());
            }
        }
        return customerTrain;
    }

    @Override
    public List<TrainOrder> orderListThings()
    {
        return trainOrderMapper.getOrderListThings();
    }

    /**
     * 火车票二维码
     * */
    @Override
    public UnionPayQRCodeResponseApi tainCodePay(HttpServletRequest request, String billNo, BigDecimal amount, String type) throws Exception {
        String notifyUrl = "http://106.38.39.137:8080/train/callback/trainVoicePayCallback";
        TrainOrder trainOrder = trainOrderMapper.selectTrainOrderByOrderId(billNo);

        if (amount.compareTo(new BigDecimal(0)) > 0){

            trainOrder.setDepositAmount(amount);
            int i = trainOrderMapper.updateByCallback(trainOrder);
            if (i <= 0){
                throw new Exception("修改订单预留款失败");
            }

            trainOrder.setPayamount(trainOrder.getPayamount().subtract(amount));

            DepositBusinessApi depositBusiness = new DepositBusinessApi();

            String token = request.getHeader("token");
            Employee employee = remoteCustomerService.getLoginEmployeeByToken(token).getData();
            if (employee == null){
                throw new Exception("登录已过期");
            }
            depositBusiness.setOperatorId(employee.getEmployeeId());
            depositBusiness.setRemark("火车票二维码支付");
            depositBusiness.setState("false");
            depositBusiness.setBusinessType(EmHelper.businessType.TRAIN.getValue());
            depositBusiness.setOrdersourceid(type);
            depositBusiness.setCustomerId(trainOrder.getJsjid());
            depositBusiness.setDetailamount(amount);
            depositBusiness.setChangetype(2l);
            depositBusiness.setLockState("false");
            depositBusiness.setOrderId(trainOrder.getOrderid());
            depositBusiness.setDrawState("false");
            Long aLong = remoteCustomerService.addReserveMoney(depositBusiness);
            if (aLong <= 0){
                throw new Exception("添加预留款记录失败");
            }

            Map<String, Object> map = new HashMap<>();
            map.put("id", aLong);
            map.put("remark", "火车票二维码支付");
            boolean b = remoteCustomerService.manageAudit(map);
            if (!b){
                throw new Exception("审核失败，请进行人工审核");
            }
        }

        if (trainOrder.getPayamount().compareTo(new BigDecimal(0)) == 0){
            if (!trainOrder.getPaymentorderstatus().equals(CustomerConstants.payd.getValue()) && !trainOrder.getStatus().equals(FlightOrderConstants.ticketing.getValue())) {
                trainOrder.setPaymentorderstatus(FlightOrderConstants.payd.toString());
                trainOrder.setStatus(FlightOrderConstants.payd.toString());
                trainOrder.setPayType(BusinessTypeConstants.UnionPayQRCode.getValue());
                Long bill = System.currentTimeMillis() / 1000;
                trainOrder.setBillNo(bill.toString());
                trainOrderService.updateTrainOrder(trainOrder);

                TrOutTicketRequest ticketRequest = new TrOutTicketRequest();
                ticketRequest.transactionid = trainOrder.getOrderpartnernumber();
                ticketRequest.orderid = trainOrder.getMerchantOrderId();

                TrOutTicketResponse ticketResponse = trainTickets.outTicket(ticketRequest);
                if (ticketResponse.success) {
                    TrainOrder train = new TrainOrder();
                    train.setOrderid(trainOrder.getOrderid());
                    train.setStatus(FlightOrderConstants.ticketing.getValue());
                    trainOrderService.updateTrainOrder(train);
                }
            }
        }

        billNo = "5676" + billNo;
        Map<String, String> map = new HashMap<>();
        map.put("billNo", billNo);
        map.put("totalAmount", String.valueOf(trainOrder.getPayamount().multiply(new BigDecimal(100)).longValue()));
        map.put("notifyUrl", notifyUrl);
        UnionPayQRCodeResponseApi qrCode = payService.getQRCode(map);
        return qrCode;
    }

    /**
     * 火车票订单列表
     * */
    @Override
    public List<TrainOrder> trainOrderList(String startDate, String finishDate) {
        String traveldate = null;
        String departuretime = null;
        String arrivaltime = null;
        if (startDate != null && !startDate.equals("") && finishDate != null && !finishDate.equals("")){
            traveldate = startDate.substring(0, 10);
            departuretime = startDate.substring(11);
            arrivaltime = finishDate.substring(11);
        }

        List<TrainOrder> trainOrders = trainOrderMapper.trainOrderList(traveldate, departuretime, arrivaltime);
        return trainOrders;
    }

    public String status(String status){
        String orderState = null;
        if (status.equals(TrainOrderEnum.processing.getValue())){
            orderState = "退票中";
        }
        else if (status.equals(TrainOrderEnum.refundTicketSuccess.getValue())){
            orderState = "退票成功";
        }
        else if (status.equals(TrainOrderEnum.refundTicketFail.getValue())){
            orderState = "退票失败";
        }
        else if (status.equals(TrainOrderEnum.unpaid.getValue())){
            orderState = "未支付";
        }
        else if (status.equals(TrainOrderEnum.payments.getValue())){
            orderState = "支付中";
        }
        else if (status.equals(TrainOrderEnum.paymentSuccessful.getValue())){
            orderState = "支付成功";
        }
        else if (status.equals(TrainOrderEnum.preSucceeded.getValue())){
            orderState = "预授权成功";
        }
        else if (status.equals(TrainOrderEnum.preConsumption.getValue())){
            orderState = "预授权消费完成";
        }
        else if (status.equals(TrainOrderEnum.preFailed.getValue())){
            orderState = "预授权失败";
        }
        else if (status.equals(TrainOrderEnum.preRevocation.getValue())){
            orderState = "预授权撤销";
        }
        else if (status.equals(TrainOrderEnum.ticketSuccessfully.getValue())){
            orderState = "出票成功";
        }
        else if (status.equals(TrainOrderEnum.ticketFail.getValue())){
            orderState = "出票失败";
        }
        else if (status.equals(TrainOrderEnum.cancelOrder.getValue())){
            orderState = "取消订单";
        }
        return orderState;
    }

    private TrainStayOutTicket queryOrder(TrainStayOutTicket ticket, TrainOrder order) {
        ticket.setDepartureStationName(order.getDeparturestationname());
        ticket.setArrivalStationName(order.getArrivalstationname());
        ticket.setDepartureTime(order.getDeparturetime());
        ticket.setArrivalTime(order.getArrivaltime());
        ticket.setTravelDate(order.getTraveldate());
        ticket.setStatus(order.getStatus());
        ticket.setTrainNumber(order.getTrainnumber());
        ticket.setAddDay(order.getAddday());
        ticket.setPoints(order.getPoints());
        ticket.setCouponId(order.getCouponId());
        ticket.setCouponAmount(order.getCouponAmount());
//        ticket.setDepositAmount(order.getDepositAmount());
        ticket.setSeatType(order.getSeattype());
        ticket.setTicketPrice(order.getTicketprice());
        ticket.setSumAmount(order.getSumamount());
        ticket.setPayAmount(order.getPayamount());
        ticket.setOrder12306Number(order.getOrder12306number());
        ticket.setMsg(order.getMsg());
        ticket.setOrdersuccess(order.getOrdersuccess());
        ticket.setRunTime(order.getRunTime());
        ticket.setLinkPhone(order.getLinkphone());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = dateFormat.format(order.getCreateTime());
        ticket.setCreateTime(format);
        order.getTrainOrderitemList().forEach(item -> {
            GuestInformation information = new GuestInformation();
            information.setOrderItemID(String.valueOf(item.getOrderitemid()));
            information.setGuestName(item.getGuestname());
            information.setIdtype(item.getIdtype());
            information.setiDNumber(item.getIdnumber());
            information.setTicketType(item.getTickettype());
            information.setSeatType(item.getSeattype());
            information.setTicketNumber(item.getTicketnumber());
            information.setTrainBox(item.getTrainbox());
            information.setSeatNo(item.getSeatno());
            information.setStatus(item.getStatus());
            List<TrainOrderAssist> orderAssists = trainOrderAssistService.queryAssistByorderItemId(item.getOrderitemid());
            if (orderAssists != null && orderAssists.size() > 0) {
                information.getTrainOrderAssists().addAll(orderAssists);
            }
            ticket.getGuestInformations().add(information);
        });
        /*R<AssistProductApi> assistProductApiR = null;
        for (TrainOrderitem trainOrderitem : order.getTrainOrderitemList()) {
            boolean bol = false;
            a:for (GuestInformation itme : ticket.getGuestInformations()) {
                if (itme.getOrderItemID().equals(trainOrderitem.getOrderitemnumber())) {
                    Insurance insurance = new Insurance();
                    assistProductApiR = remoteCustomerService.queryAssistProduct(trainOrderitem.getInsuranceid());
                    if (assistProductApiR.getCode() == 200 && assistProductApiR.getData() != null) {
                        insurance.setName(assistProductApiR.getData().getName());
                        insurance.setInsuranceID(trainOrderitem.getInsuranceid());
                        insurance.setInsuranceAmount(trainOrderitem.getInsuranceamount());

                        itme.getInsurances().add(insurance);
                    }
                    bol = true;
                    break a;
                }
            }
            if (!bol) {
                GuestInformation information = new GuestInformation();
                information.setInsurances(new ArrayList<>());
                information.setOrderItemID(trainOrderitem.getOrderitemnumber());
                information.setGuestName(trainOrderitem.getGuestname());
                information.setiDNumber(trainOrderitem.getIdnumber());
                information.setTicketType(trainOrderitem.getTickettype());
                information.setSeatType(trainOrderitem.getSeattype());
                information.setTicketNumber(trainOrderitem.getTicketnumber());
                information.setTrainBox(trainOrderitem.getTrainbox());
                information.setSeatNo(trainOrderitem.getSeatno());
                information.setStatus(trainOrderitem.getStatus());
                information.setIdtype(trainOrderitem.getIdtype());

                Insurance insurance = new Insurance();
                assistProductApiR = remoteCustomerService.queryAssistProduct(trainOrderitem.getInsuranceid());
                if (assistProductApiR.getCode() == 200 && assistProductApiR.getData() != null) {
                    insurance.setName(assistProductApiR.getData().getName());
                    insurance.setInsuranceID(trainOrderitem.getInsuranceid());
                    insurance.setInsuranceAmount(trainOrderitem.getInsuranceamount());

                    information.getInsurances().add(insurance);
                }
                ticket.getGuestInformations().add(information);
            }
        }*/
        for (TrainOrderRefundrecord refundrecord : order.getRefundrecords()) {
            TrainOrderRefundrecordVo refundrecordVo = new TrainOrderRefundrecordVo();
            refundrecordVo.setRecordid(refundrecord.getRecordid());
            refundrecordVo.setRefundamount(refundrecord.getRefundamount());
            refundrecordVo.setName(refundrecord.getName());
            refundrecordVo.setMemo(refundrecord.getMemo());
            refundrecordVo.setStatus(refundrecord.getStatus());
            if (refundrecordVo.getRecordid() != null)
                ticket.getRefundrecords().add(refundrecordVo);
        }

        if (order.getSkillamount() != null && !order.getSkillamount().equals("")){
            ticket.setServiceCharge(order.getSkillamount().toString());
        }
        if (order.getCreateTime() != null && !order.getCreateTime().equals("")){
            ticket.setScheduledTime(dateFormat.format(order.getCreateTime()));
        }

        ticket.setReservation(order.getOpemployeename());
        /*if (assistProductApiR.getData() != null) {
            if (assistProductApiR.getData().getSalePrice() != null && !assistProductApiR.getData().getSalePrice().equals("")){
                ticket.setInsurance(assistProductApiR.getData().getSalePrice().toString());
            }
        }*/

        ticket.setPaymentMethod(order.getPayType());
        ticket.setTransactionNum(order.getPlatformtradenumber());
        if (order.getOrdertype() != null && !order.getOrdertype().equals("")){
            ticket.setOrderType(order.getOrdertype().toString());
        }

        ticket.setContact(order.getLinkphone());
        if (order.getDeletetime() != null && !order.getDeletetime().equals("")){
            ticket.setDeleteTime(dateFormat.format(order.getDeletetime()));
        }

        ticket.setRemark(order.getMemo());

        List<TrainOrderOperation> trainOrderOperations = trainOrderOperationMapper.trainOrderOperationList(Long.valueOf(order.getOrderid()));

        List<OperateVo> operateVoList = new ArrayList<>();
        if (trainOrderOperations != null && trainOrderOperations.size() > 0){
            for (TrainOrderOperation trainOrderOperation : trainOrderOperations) {
                OperateVo operateVo = new OperateVo();
                operateVo.setTitle(trainOrderOperation.getOperationname());
                operateVo.setName(trainOrderOperation.getOpemployeename());
                if (trainOrderOperation.getCreateTime() != null && !trainOrderOperation.getCreateTime().equals("")){
                    operateVo.setTime(dateFormat.format(trainOrderOperation.getCreateTime()));
                }

                operateVo.setRemark(trainOrderOperation.getMemo());
                operateVoList.add(operateVo);
            }
        }
        ticket.setOperateVoList(operateVoList);
        return ticket;
    }
}
